Search code examples
javascriptreactjsnext.jsjwt

Is it safe to keep access token in NextAuth session?


I have a custom API from Nodejs with Expressjs. I am using nextAuth to authenticate user in Next.js application. On login, I call my login API route and save the date in nextAuth session and can access it via the useSession hook. When making an api request for protected api routes, I pass the access token saved in the next session via the header. I am also storing the refresh token in the session object, then keep it in localstorage for refresh route that is used to regenerate access token when making api call. This is working fine. I want to know if this is safe for a production grade application.

const authOptions: NextAuthOptions = {
session: {
    strategy: "jwt",
  },

  providers:[
    CredentialsProvider({
        type: "credentials",
        credentials: {},

       async authorize(credentials, req){
            const { username, password } = credentials as {
                username: string;
                password: string;
              };

              if(!credentials){
                return null
              }
              const userData = {
                username: username,
                password: password
              }
            

              try {
                
                const response = await axios.post(`${BASE_URL}/login`, userData);
                if(response?.data){
                  
                  const user: jwtDecodedAttributes = jwt_decode(response?.data?.userToken);
                  console.log(user, userData, 'hey');
                  return {
                    id: user.userId,
                    name: user.username,
                    role: user.role,
                    profilepicture: user.profilepicture,
                    iat: user?.iat,
                    exp: user?.exp,
                    username: user?.username,
                    token: response?.data?.userToken,
                    email: user.email,
                    userId: user?.userId,
                    refresh: response?.data.userRefreshToken
                  };
            }
             
                
              } catch (error) {
                
                
              }
              return null
        }
    })
  ],

  pages: {
    signIn: "/login",
  },

callbacks:{
 async jwt({token, user}){

      return {...token, ...user} ;
  },

 async session({session, token, user}){
    
    session.user = token
   
    
    return session
 }
}
};


export default NextAuth(authOptions);

I can access the data in my Next.js app this way:

  const { status, data } = useSession();
   console.log(data?.user.token)

Solution

  • I usually do that too, so I would say yes, it is generally safe to keep access tokens in NextAuth sessions. NextAuth sessions are encrypted using JSON Web Tokens (JWTs).

    Also, session storage is pretty secure location. I would also rotate the tokens regularly for security reasons and avoid using them for purpose other than authenticated requests.