简体   繁体   English

API 中的 JWT 令牌存储在哪里

[英]Where to store JWT token from an API in next-auth

I implemented this in next-auth following some tutorial online我按照一些在线教程在 next-auth 中实现了这个

import NextAuth from "next-auth"
import Providers from "next-auth/providers";
const https = require('https');

export default NextAuth({
  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: "Email", type: "email" },
        password: {  label: "Password", type: "password" }
      },
      async authorize(credentials) {
        const url = 'https://localhost/auth';

        const httpsAgent = new https.Agent({
          rejectUnauthorized: false,
        });

        const res = await fetch(url, {
          method: 'POST',
          body: JSON.stringify(credentials),
          agent: httpsAgent,
          headers: {
            "Content-Type": "application/json"
          }
        })
        const user = await res.json();

        if (res.ok && user) {
          return user;
        } else {
          return null;
        }
      }
    }),
    // ...add more providers here
  ],
  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user?.type) {
        token.status = user.type
      }
      if (user?.username) {
        token.username = user.username;
      }

      return token
    },

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

pretty standard.相当标准。 https://localhost/auth return an object like this (I called it user for now) https://localhost/auth 像这样返回一个 object(我暂时称它为用户)

{
  token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2MzY0MTE4NjEsImV4cCI6MTYzNjQxNTQ2MSwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoiZXJuYTM5QHdlYmVyLmNvbSJ9.Abenx1GhB-_d9LVpLfa2NYp62Lbw6U65EUQowA0jA_aykx1m-BlBR_YBcL4XIJsknJ99NN8Ees4Zxdsphfhjs7du4TR2MgTITHYy-BYjBX9CsluVSBpm-L7c-oK5vu70eumAy1ixy5MKOTN2EQYCm65RszSheIwZ4LN8vSuzxzZuLszRG9nbpauiHDpYCeLrNeNkz4lhTicfWkdPafR8vhqt4MIeCl-kxbMqc35UNmglzE7n-b9zVh4OhU7bSCoPKZySL5c4GSf7UFFD-mXIe6s9b4qYSXJuLpdspFJSgP7UoEGP1gh8fTb5MDZREYyZOpK3BMU8EdwokngVR9zrbw'
}

I would like to know how to store this token to be used in further calls to my API. I can see the token object in the session callback is我想知道如何存储此令牌以用于进一步调用我的 API。我可以在 session 回调中看到令牌 object 是

{ iat: 1636411862, exp: 1639003862 }

so next-aut is not doing this for me.所以 next-aut 没有为我做这件事。 Should I set an httpOnly cookie in the session callback?我应该在 session 回调中设置一个 httpOnly cookie 吗? or right after或紧随其后

if (res.ok && user) {

just before to return user?就在返回用户之前?

I found a way just updating the callbacks:我找到了一种只更新回调的方法:

  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user?.token) {
        token.token = user.token;
      }
      return token;
    },

    async session(session, token) {
      return session;
    }
  }

in this way the token from the API is now stored in a httpOnly cookie called __Secure-next-auth.session-token (assuming the token from the API is in the format like above).通过这种方式,来自 API 的令牌现在存储在名为__Secure-next-auth.session-token的 httpOnly cookie 中(假设来自 API 的令牌采用上述格式)。

in dart, save the jwt token in local storage.在 dart 中,将 jwt 令牌保存在本地存储中。 you can then access local storage and persist the token between session.然后,您可以访问本地存储并在会话之间保留令牌。

otherwise store the jwt token in a singleton or a provider and assess it during the session.否则将 jwt 令牌存储在单例或提供程序中,并在会话期间对其进行评估。

You could save it to a cookie.您可以将其保存到 cookie。 I've found this to be a very good module.我发现这是一个非常好的模块。 https://github.com/pillarjs/cookies https://github.com/pillarjs/cookies

如果您将 JWT 存储在 cookie 中,那么每次调用 API 时,您都可以检查 cookie 标头以查看是否有它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM