[Nuxt.JS]access the $auth object in the context from plugin js - axios

I want to access the $auth object in the context from the js defined under 'plugins/', but I can't.
https://auth.nuxtjs.org/api/auth.html#auth
This module globally injects $auth instance, meaning that you can access it anywhere using this.$auth. For plugins, asyncData, fetch, nuxtServerInit and Middleware, you can access it from context.$auth
It is described above, but my code (axios-interceptor.js) cannot access $auth from context (it is undefined).
What does it take to be able to access it?
plugins/axios-interceptor.js
export default function (context) {
const { $axios, route, redirect } = context
$axios.interceptors.response.use(
function (response) {
return response
},
function (error) {
const code = parseInt(error.response && error.response.status)
const thisRoutePath = route.path
if ([401, 403].includes(code)) {
if (thisRoutePath !== '/') {
redirect('/?login')
}
}
return Promise.reject(error)
}
)
}
nuxt.config.js
export default {
plugins: [
'#/plugins/axios-interceptor.js'
],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
'#nuxtjs/auth'
],
axios: {
baseURL: BASE_URL
},
auth: {
cookie: false,
autoFetchUser: false,
redirect: {
login: '/login',
logout: '/login',
callback: '/callback',
home: '/home'
},
strategies: {
local: {
endpoints: {
login: { url: BACKEND_API_PATH_BASE + '/api/v1/login/', method: 'post', propertyName: 'token' },
user: { url: BACKEND_API_PATH_BASE + '/api/v1/users/me', method: 'get', propertyName: false },
logout: false
},
},
}
},
router: {
middleware: [
'auth'
]
},
The reason I want to access $auth in axios-interceptor.js is that I want to execute $auth.logout() in the if ([401, 403].includes(code)) { block and remove the token.

I am now able to access $auth by doing the following
export default {
// plugins: [
// '#/plugins/axios-interceptor.js' ########### REMOVE ###########
// ],
:
(Ommit)
:
auth: {
:
(Ommit)
:
plugins: [
'#/plugins/axios-interceptor.js' // ########### ADD ###########
]
},
(Ommit)
:
}
The things I needed to do were listed below.
https://auth.nuxtjs.org/recipes/extend.html

Related

NextJS send data on redirect inside getServerSideProps

Is there a posibility to send data with redirect inside getServerSideProps function similar way as in next.config.js (you cannot pass hidden queries as far as I know inside next config file).
export const getServerSideProps = async (context) => {
const id = context.params.id;
return {
redirect: {
destination: '/my-work',
permanent: false,
has: [
{
type: 'query',
value: id
}
]
},
props: {
}
}
}
I want to pass hidden query to another page so this only works as middleware redirection as I am comming on this page from email template. But has object is not working in getServerSideProps function.
Is there any other ways to achieve that?
Thanks for your help!
This is from the official documentation.
module.exports = {
async redirects() {
return [
// if the header `x-redirect-me` is present,
// this redirect will be applied
{
source: '/:path((?!another-page$).*)',
has: [
{
type: 'header',
key: 'x-redirect-me',
},
],
permanent: false,
destination: '/another-page',
},
// if the source, query, and cookie are matched,
// this redirect will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// destination since value is provided and doesn't
// use a named capture group e.g. (?<page>home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
permanent: false,
destination: '/another/:path*',
},
// if the header `x-authorized` is present and
// contains a matching value, this redirect will be applied
{
source: '/',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
permanent: false,
destination: '/home?authorized=:authorized',
},
// if the host is `example.com`,
// this redirect will be applied
{
source: '/:path((?!another-page$).*)',
has: [
{
type: 'host',
value: 'example.com',
},
],
permanent: false,
destination: '/another-page',
},
]
},
}
You can compare the params with it. For more details, visit here

useSession stays in loading state after sign-in using REST API

I am using the Credentials provider and next-auth 4.3.1
I go to page /protected
This page does useSession({ required: true, onUnauthenticated: () => router.push('/login?redirect=/protected') })
I login on the login page I got redirected too with this code:
const { data: { csrfToken } } = await axios.get('/api/auth/csrf');
const res = await axios
.post(
'/api/auth/callback/credentials',
{
json: true,
csrfToken,
redirect: false,
email: form.email,
password: form.password
},
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
);
router.push(router.query.redirect || '/');
After succesfully logging in, notice it pushes back router.push(router.query.redirect), so it takes me back to /protected
However useSession returns { data: undefined, status: loading } and triggers onUnauthenticated, taking me back to the login page
Now, I don't login again, I just type in URL bar https://localhost:3000/protected it will load the protected page and useSession properly finds the logged-in session.
Is there something I have to do to make useSession see signIn was just called?
Here is my [...nextauth].ts:
const handler = NextAuth({
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt'
},
debug: process.env.NODE_ENV === 'development',
providers: [
CredentialsProvider({
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' }
},
async authorize(credentials, req) {
////// removed
}
})
],
pages: {
signIn: '/login'
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.user = { id: user.id };
}
return token;
},
async session({ session, token }) {
if (session?.user) {
session.user.id = token.user.id;
}
return session;
}
}
});

How to redirect from a subdomain of a Nextjs app?

To redirect from one page to another in a nextjs app update next.config.js
module.exports = {
async redirects() {
return [
{
source: '/shop',
destination: '/',
permanent: true,
},
]
},
}
Can you redirect from a subdomain within the next.config.js? Something like:
module.exports = {
async redirects() {
return [
{
source: 'shop.mydomain.com',
destination: '/shop',
permanent: true,
},
]
},
}

How do I add auth headers to axios hooks requests?

I am working with React Hooks and I want to use the axios hooks package to send an image to Cloudinary.
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT'
},
{ manual: true }
)
The docs say nothing about headers?
I believe you are looking for this:
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
},
{ manual: true }
)
docs: https://github.com/axios/axios#request-config

Unknown authentication strategy jwt in hapijs jwt authentication

I am using hapi-auth-jwt for authentication purpose
But on the login when i use auth strategy as jwt, it shows Unknown authentication strategy jwt in /login
I am using glue
Here is my code
manifest.js:
module.exports = {
server : {},
connections : [
{
host: apiConfig.server.host,
port: apiConfig.server.port
},
],
registrations : [
{
'plugin': {
register: 'hapi-auth-jwt',
},
},
]
};
server.js:
glue.compose(manifest, manifestOptions, (error, server) => {
if(error)
throw error;
mongoose.connect("mongodb://" + apiConfig.database.host + '/' + apiConfig.database.dbname, (error) => {
if(error)
console.log(error);
else
console.log('mongodb connected');
});
server.app.assetsPath = Path.resolve(__dirname, '../assets');
server.start(() => {
console.log("Api server running " + server.info.uri);
});
server.auth.strategy('jwt', 'jwt', {
key: apiConfig.authentication.secretKey,
verifyOptions: {
algorithms: ['HS256']
}
});
}
route.js:
{
method : 'POST',
path : '/login',
config : {
auth: {
strategy: 'jwt',
},
tags : ['api'],
description: 'Customer login',
plugins : {
'hapi-swagger': {
payloadType: 'form'
}
},
/*validate : {
failAction: Relish.failAction,
options : {
abortEarly: false
},
payload : loginSchema
},*/
},
handler: handler.loginHandler
}
I was loading my route in the glue manifest, after that only I am registering my auth. So I included the auth registration in glue's manifest before the route registration