Search code examples
reactjsnext.jsnext-auth

How to decrypt session-token (Next-auth JWT token)


I am controlling user authentification in my next app with next-auth library

I am using the credentials provider. First I call the login endpoint which returns the user informations then I take the access token and put it inside the token given by next-auth callback.

this is my code in [...nextauth].js

const authOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      type: "credentials",
      credentials: {},
      async authorize(credentials, req) {
        const { email, password } = credentials;
        const result = await axios.post(
          `http://127.0.0.1:5000/user/login`,
          {
            email,
            password,
          },
          {
            headers: { "Content-Type": "application/json" },
            withCredentials: true,
          }
        );
        return {
          accessToken: result.data.accessToken,
        };
      },
    }),
  ],
  callbacks: {
    async jwt({ user, token }) {
    if (user?.accessToken) {
    token.value = user.accessToken;
      }
    console.log(token); //<-- output below
    return token;
    },
  },
};

output :

{
  value: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzOTZiMTlhYTczMmUzMzYwMjU2ZjBlMiIsImlhdCI6MTY3NTAyMzEwNSwiZXhwIjoxNjc1MTA5NTA1fQ.5kdPmeLCpwbJBjtzKMhe5QMNEx75ThiDKm75PN0vjoc',
  iat: 1675023106,
  exp: 1675109506,
  jti: 'd9108700-1b5f-4bd3-8d31-0c36f38d9fcb'
}

Now in getServerSideProps I can get it from the request because it is sent in Cookie

export async function getServerSideProps(context) {
  console.log(context.req.cookies["next-auth.session-token"]); // <-- output in Blockquote
  return {
   // does not matter
  };
}

I get this :

eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..6ryJ60GPcDLq9aWG.4oWlJbecyWUnbZYJiv6z0eAuFmRFSfEn4fQSlh1FTjlPiiDGZASA4UwqXNEHRpRMG6HRPRDcsUUCHBBzaV8JwCEetgSYJcSrZ5CK_AhyvFKUlKY-TpHSNDnmCI8ZS4y2nV_Xl0NqvMU3vA-D8gXtT5UcOrJLlN5dMe7S9xZo8vhr-gpohcEhKOefUgDjTmMYmBf190OLl0TY599FkJwpoeSFozAwavwbOZGQOxYVbsj3KTibsfE37juyqnDaiV_t59bWroGjz2d5kHLxfkpQB0IKYRnAH8sXbG7dDZUVLT1UQUN_FrjYpkFrQgxC7MmWZtCccQs-FsBXY7EbiYmJKIddpOeN1Q.1kas8bGE_O7IkEDiilxiZw

Now I want to decrypt this token to get its proprety value (which is the accessToken) and use it.

is it possible to decrypt it with javascript ? Thank you for your attention !


Solution

  • You've parsed ["next-auth.session-token"] from req.cookies. Then now. You could decrypt the token by using decode method from next-auth/jwt to get JSON payload.

    import { decode } from 'next-auth/jwt';
    

    Here's an example.

    import { decode } from 'next-auth/jwt';
    
    export async function getServerSideProps(context) {
      const sessionToken = context.req.cookies['next-auth.session-token'];
    
      const decoded = await decode({
        token: sessionToken,
        secret: process.env.NEXTAUTH_SECRET,
      });
    
      // decoded JSON will be like :
      /**
       * {
       *  name: 'John Doe',
       *  email: '...',
       *  image: '...'
       * }
       */
    }