NextAuth Azure AD B2C - NextJS Pages Typescript 中未定义访问令牌

问题描述 投票:0回答:1

我一直在尝试在会话中附加访问令牌,但我没有获得访问令牌的值。

我不确定我做的一切是否正确:

import util from "node:util";
import NextAuth, { AuthOptions } from "next-auth";
import AzureADB2CProvider from "next-auth/providers/azure-ad-b2c";

export const authOptions: AuthOptions = {
    providers: [
        AzureADB2CProvider({
            tenantId: process.env.AZURE_AD_B2C_TENANT_NAME,
            clientId: process.env.AZURE_AD_B2C_CLIENT_ID ?? "",
            clientSecret: process.env.AZURE_AD_B2C_CLIENT_SECRET ?? "",
            primaryUserFlow: process.env.AZURE_AD_B2C_PRIMARY_USER_FLOW,
            authorization: {
                params: { scope: "offline_access openid" },
            },
            token: {
                params: { scope: "openid profile user.Read.All email" },
            },

            // Attach UserProfileID into the Session Profile while keeping defaults
            profile(profile) {
                return {
                    id: profile.sub,
                    name: profile.name,
                    email: profile?.emails?.[0],
                    userProfileID: profile?.extension_UserProfileID,
                    image: null,
                };
            },
        }),
    ],
    
    callbacks: {
        async signIn({ profile }) {
            // It's a newly created account when extension_UserProfileID does not exist
            if (profile && !("extension_UserProfileID" in profile)) {
                return "/?newUser=1";
            } else {
                return true;
            }
        },
        async jwt({ token, user, account, profile }) {
            // I should get the value for access token in the account
            console.log("account", account);
            // On JWT Token, Attach id_token from account - which exists only on SignIn
            if (account && user) {
                token.id_token = account.id_token;
                token.userProfileID = user.userProfileID;
            }

            return token;
        },
        async session({ session, token }) {
            // Expose userProfileID unto the Session
            if ("userProfileID" in token) {
                session.user.userProfileID = Number(token.userProfileID);
            }

            // Include the ID Token in the Session
            if ("id_token" in token) {
                session.user.idt = String(token.id_token ?? "");
            }

            // To do: Dynamically load Role based on API
            session.user.role = "ServiceRequest";

            return session;
        },
    },

    logger: {
        error(code, metadata) {
            console.error(code, metadata);
        },
        warn(code) {
            console.warn(code);
        },
        debug(code, metadata) {
            console.debug(code, util.inspect(metadata, true, null, true));
        },
    },
};

export default NextAuth(authOptions);

这是AD B2C中的访问令牌配置:

Implicit grant and hybrid flows

然后这是我将进入帐户中的控制台:

account: {
    provider: 'azure-ad-b2c',
    type: 'oauth',
    providerAccountId: '8e22.......',
    id_token: 'eyJraW.......',
    token_type: 'Bearer',
    not_before: 1705946179,
    id_token_expires_in: 3600,
    profile_info: 'eyJraW.......',
    scope: 'offline_access openid',
    refresh_token: 'eyJraW.......',
    refresh_token_expires_in: 86400
  }

我尝试了这里提到的所有内容

reactjs azure next.js azure-ad-b2c next-auth
1个回答
0
投票

注意:要在 Azure AD B2C 中获取访问令牌,您必须调用 API。范围必须是这样的

scope=https://xxx.onmicrosoft.com/api/read openid offline_access
。参考这个MsDoc

对于 sample,公开如下 API:

enter image description here

并为API授予API权限:

enter image description here

现在将 scope 作为

scope: https://srib2caadtenant.onmicrosoft.com/15b78f43-ca4f-4cea-8989-4d7f45e9d01c/test.read.all openid offline_access
传递以获取访问令牌:

我使用以下参数通过 Postman 生成了 访问令牌

https://b2caadtenant.b2clogin.com/b2caadtenant.onmicrosoft.com/B2C_1_testb2c/oauth2/v2.0/token

client_id:ClientID
grant_type:authorization_code
scope:https://b2caadtenant.onmicrosoft.com/ClientID/test.read.all openid offline_access
code:code
redirect_uri:https://jwt.ms
client_secret:ClientSecret

enter image description here

修改如下代码以获取访问令牌:

export const authOptions: AuthOptions = {
    providers: [
        AzureADB2CProvider({
            tenantId: process.env.AZURE_AD_B2C_TENANT_NAME,
            clientId: process.env.AZURE_AD_B2C_CLIENT_ID ?? "",
            clientSecret: process.env.AZURE_AD_B2C_CLIENT_SECRET ?? "",
            primaryUserFlow: process.env.AZURE_AD_B2C_PRIMARY_USER_FLOW,
            authorization: {
                params: { scope: "offline_access openid" },
            },
            token: {
                params: { scope: "https://b2caadtenant.onmicrosoft.com/ClientID/test.read.all openid profile user.Read.All email" },
            },
© www.soinside.com 2019 - 2024. All rights reserved.