I'm trying to develop a plugin for oidc-client to work with nuxt because @nuxtjs/auth does not work with my identity provider. Basically everything is working the only problem is that I need to add a custom property to the components and access it in the middleware to check if auth is enabled. I've been looking at another plugins for guidance and this is what I ended up with:
plugins/user-manager.ts
export default (context: Context, inject: Inject) => {
if (context.ssrContext) return
const userManager = new UserManager({
client_id: 'test',
authority: 'https://ouath.test.net',
automaticSilentRenew: true,
response_type: 'code',
scope: 'openid email phone role user',
redirect_uri: 'http://localhost:4200/login/authorize',
post_logout_redirect_uri: 'http://localhost:4200',
silent_redirect_uri: window.location.origin + '/silent-refresh.html'
});
inject('auth', userManager);
context.$axios.onRequest(config => {
return userManager.getUser().then(user => {
if (user && user.access_token)
config.headers.Authorization = 'Bearer ' + user?.access_token;
return config
});
});
}
middleware/auth.ts
import {Context} from '@nuxt/types';
export default async function (context: Context) {
if (context.ssrContext) return
console.log(context)
if (context.app.auth === false) return
const user = await context.$auth.getUser()
if (!user || user.expired) {
await context.$auth.signinRedirect()
}
}
example component
import axios from "axios"
export default {
auth: false,
components: {
},
data() {
return {
items: [],
cards: []
};
},
mounted() {
},
};
The problem is that in the middleware the line if (context.app.auth === false) return always returns true because context.app.auth is undefiend, but the component has the auth: false property in it. How can I access the auth property from the middleware?
!context.app.auth
(true
if it's falsy) rather thancontext.app.auth === false
. – kissu