next.js 使用auth0在下一次认证时从会话中设置和获取令牌

3htmauhk  于 2023-11-18  发布在  其他
关注(0)|答案(2)|浏览(137)

我有一个nextjs应用程序。我使用nextauthAuth0Provider进行身份验证。
我希望能够获得令牌并通过我的API请求的头发送它。我可以在登录回调上记录和查看令牌,但我无法在会话回调中访问相同的令牌。我想我错过了一些东西,我将感谢任何帮助我可以得到。

[...nextauth].js

import NextAuth from 'next-auth';
import Auth0Provider from 'next-auth/providers/auth0';

export default NextAuth({
  providers: [
    Auth0Provider({
      clientId: 'pF....H',
      clientSecret: 'Mh.....vAbQ',
      issuer: 'https://dev-xceoh....8u8.us.auth0.com',
      redirectUri: `http://localhost:3000/api/auth/callback/auth0`,
      idToken: true,
      token: {
        params: {
          audience: 'https://dev-xce.....r8u8.us.auth0.com/api/v2/'
        }
      },
      authorization: {
        params: {
          audience: encodeURI('https://dev-x......r8u8.us.auth0.com/api/v2/')
        }
      }
    }),
  ],
  secret: '306.................024',
  session: {
    strategy: 'jwt',
    secret: process.env.NEXTAUTH_SECRET
  },
  jwt: {},
  callbacks: {
    session: async ({ session, token }) => {
      if (token) {
        session.user = token.user;
        session.accessToken = token.accessToken;
        session.error = token.error;
      }
      return session;
    },
    async redirect(url) {
      if (typeof url === 'string') {
        return url.startsWith('http://localhost:3000') ? url : 'http://localhost:3000';
      } else {
        return 'http://localhost:3000';
      }
    },
    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token
      }
      return token
    },
    async signIn( profile) {
      if (profile?.account?.access_token) { // Check if the token exists in the account object
        console.log('ACCESS TOKEN!!!!!!!:', profile.account.access_token); // Log the token to the console
        return '/apps';
      }
      return true;
    },

  },
});

字符串

Index.js

<div className="flex flex-col items-center justify-center mb-4">
  <img src={logoUrl} alt="Logo" />
  <a href="/api/auth/signin" className="mt-2 text-blue-500 hover:underline"
    onClick={(e) => {
      e.preventDefault();
      signIn("auth0");
    }}>
  Log in
  </a>
</div>

35g0bw71

35g0bw711#

我可以使用getSession()hook来获取它。

import { getSession } from 'next-auth/react';

  export function authHeaders() {
    if (typeof window !== 'undefined') {
      return getSession()
        .then(session => {
          const token = session.accessToken;
          console.log("THE TOKEN BEING SENT IS!!!!!!!!!!",token)
          const authToken = `Bearer ${token}`;
          return {
            headers: {
              Accept: 'application/json',
              'content-type': 'application/json',
              Authorization: authToken,
            },
          };
        })
        .catch(error => {
          console.error('Error fetching session:', error);
          // Handle error case: return headers without Authorization if token retrieval fails
          return {
            headers: {
              Accept: 'application/json',
              'content-type': 'application/json',
            },
          };
        });
    }
  }

字符串

6jjcrrmo

6jjcrrmo2#

您可以在组件中使用useSession()来访问会话和令牌。
Home.js

import { useSession } from "next-auth/react";

const Home = () => {
  const { data: session, status } = useSession({ required: true });

  useEffect(() => {
    console.log("accessToken:", session.accessToken);
  }, []);
};

字符串

相关问题