next.js 下一个验证如何解密会话令牌

z18hc3ub  于 2023-01-05  发布在  其他
关注(0)|答案(1)|浏览(122)

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 in the image
    return token;
    },
  },
};

this is the output :

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.
When I try to decrypt it with https://jwt.io/ I get this warning :
Looks like your JWT payload is not a valid JSON object. JWT payloads must be top level JSON objects
is it possible to decrypt it with javascript ?
thank you for your attention !

lmvvr0a8

lmvvr0a81#

此函数位于next-auth/jwt模块内部:

async function decode(params) {
  const {
    token,
    secret
  } = params;
  if (!token) return null;
  const encryptionSecret = await getDerivedEncryptionKey(secret);
  const {
    payload
  } = await (0, _jose.jwtDecrypt)(token, encryptionSecret, {
    clockTolerance: 15
  });
  return payload;
}

由于没有导出,您必须导出所有模块

import jwt from "next-auth/jwt"
 // since you reached the token inside getServerSidePrps passed here
 jwt.decode(token,passYourSecret)

相关问题