You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+ASP.NET Core中Microsoft认证实现问题求助

Microsoft认证实现问题:React登录后无法获取有效Token,ASP.NET Core API验证失败

React前端问题:获取的Token签名无效

  • 问题表现:使用@azure/msal-browser的loginRedirect能正常完成登录,但调用acquireTokenSilent获取的Token在jwt.io上显示签名无效。
  • 问题代码:
const request = {
    scopes: ["User.Read"],
    account: accounts[0]
};

instance.acquireTokenSilent(request).then(response => {
    console.log(response.accessToken);
}
  • 当前配置(authConfig.js):
import { LogLevel } from "@azure/msal-browser";
export const msalConfig = {
    auth: {
        clientId: "c0000d4e-0000-0000-0000-425000032721",
        authority: "https://login.microsoftonline.com/eace0000-0000-0000-0000-6dced0000bc/oauth2/v2.0/token",
        redirectUri: "https://example.com/signin-oidc",
    },
    cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: false,
    },
    system: {
        loggerOptions: {
            loggerCallback: (level, message, containsPii) => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                    default:
                        return;
                }
            }
        }
    }
};

export const loginRequest = {
    scopes: ["api://c0000d4e-0000-0000-0000-425000032721/.default"]
};

export const graphConfig = {
    graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};
  • 修复思路:
    • 修正authority地址:authority应该是https://login.microsoftonline.com/eace0000-0000-0000-0000-6dced0000bc,不需要带/oauth2/v2.0/token,MSAL会自动拼接正确的Token端点。
    • 匹配正确的Scope:如果要调用自定义API,acquireTokenSilent的scopes应该用["api://c0000d4e-0000-0000-0000-425000032721/.default"],而不是User.Read(这是Microsoft Graph的权限,和自定义API无关)。
    • 验证账户有效性:调用instance.getAllAccounts()确认accounts[0]是已登录的有效账户,避免传入空或错误的账户对象。

ASP.NET Core后端问题:Client Credentials Token验证失败

  • 问题表现:通过curl用Client Credentials流获取了签名有效的Token,但调用带[Authorize]的API时返回Bearer error="invalid_token"。
  • 用于获取Token的curl命令:
curl -X POST https://login.microsoftonline.com/eace0000-0000-0000-0000-6dced0000bc/oauth2/v2.0/token -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=c0000d4e-0000-0000-0000-425000032721" -d scope=api://c0000d4e-0000-0000-0000-425000032721/.default -d "client_secret=jtS0000SC000lorem0000000DjULkm00001aS9" -d "grant_type=client_credentials"
  • 当前Program.cs配置:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(options =>
            {
                builder.Configuration.Bind("AzureAd", options);
                options.Events = new JwtBearerEvents();
            }, options => { builder.Configuration.Bind("AzureAd", options); });
  • appsettings.json配置:
"AzureAd": {
    "Instance": "https://example.com/",
    "Domain": "local.example.com",
    "TenantId": "eace0000-0000-0000-0000-6dced0000bc",
    "ClientId": "c0000d4e-0000-0000-0000-425000032721",
    "Scopes": ".default", // also tried api://clientid/.default
    "CallbackPath": "/signin-oidc"
  }
  • 修复思路:
    • 修正Instance地址:Instance必须是https://login.microsoftonline.com/,因为Token是Azure AD颁发的,后端需要从这个地址获取公钥来验证签名,自定义域名https://example.com/会导致无法获取正确的验证密钥。
    • 指定正确的Audience:Client Credentials流获取的Token的受众(aud)是api://c0000d4e-0000-0000-0000-425000032721,需要在配置中明确指定。可以在appsettings.json的AzureAd节点添加"Audience": "api://c0000d4e-0000-0000-0000-425000032721",或者在Program.cs中手动设置:
      options.TokenValidationParameters.ValidAudience = "api://c0000d4e-0000-0000-0000-425000032721";
      
    • 移除无用配置:CallbackPath是用于OpenID Connect登录流程的,对于JWT Bearer认证不需要,建议从appsettings.json中删除该配置项。
    • 验证Issuer匹配:确保Token的issuer是https://login.microsoftonline.com/eace0000-0000-0000-0000-6dced0000bc/v2.0,后端配置的Instance+TenantId要和这个值一致。

内容的提问来源于stack exchange,提问作者darkiyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:04:55