reactjs 如何解密会话令牌(下一个验证JWT令牌)

6psbrbz9  于 2023-03-17  发布在  React
关注(0)|答案(2)|浏览(151)

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 !

lmvvr0a8

lmvvr0a81#

有一个内置的helper方法getToken()可以实现这一点
为方便起见,此帮助器函数还能够读取和解码从Authorization:“承载令牌”HTTP标头。

import { getToken } from "next-auth/jwt";
const secret = 'MY_SECRET';

export default async function handler(req, res) { 
  const token = await getToken({ req, secret })
  console.log("JSON Web Token", token)
  res.end()
}

如果使用NEXTAUTH_SECRET env变量,我们会检测到它,实际上不需要secret

export default async function handler(req, res) { 
  const token = await getToken({ req })
  console.log("JSON Web Token", token)
  res.end()
}
dldeef67

dldeef672#

您已经从req.cookies解析了["next-auth.session-token"]。现在,您可以使用next-auth/jwt中的decode方法解密令牌,以获取JSON有效负载。

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

这里有一个例子。

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: '...'
   * }
   */
}

相关问题