admin管理员组

文章数量:1278789

I implemented this in next-auth following some tutorial online

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)

{
  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

{ iat: 1636411862, exp: 1639003862 }

so next-aut is not doing this for me. Should I set an httpOnly cookie in the session callback? or right after

if (res.ok && user) {

just before to return user?

I implemented this in next-auth following some tutorial online

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)

{
  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

{ iat: 1636411862, exp: 1639003862 }

so next-aut is not doing this for me. Should I set an httpOnly cookie in the session callback? or right after

if (res.ok && user) {

just before to return user?

Share Improve this question asked Nov 8, 2021 at 23:01 user3174311user3174311 1,9938 gold badges36 silver badges78 bronze badges 1
  • Does this answer your question? How to use JWT to store data in NextAuth – juliomalves Commented Nov 9, 2021 at 23:15
Add a ment  | 

2 Answers 2

Reset to default 8

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).

If you store the JWT in the cookies so every time you're calling your API you could check the cookie header to see if you have it.

本文标签: javascriptWhere to store JWT token from an API in nextauthStack Overflow