如何通过 React 在 ASP.NET Core 中使用 Microsoft 身份验证

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

我目前正在尝试在 ASP.NET Core 上运行 Microsoft 身份验证。基本上我想登录前端(React)并使用我的自定义 API。
一个电话可能看起来像

https://example.com/API/returnHelloWorld

现在在 React 中,我使用

@azure/msal-browser
进行登录。
通过使用按钮,我可以调用
instance.loginRedirect(loginRequest)
,它可以工作并且我可以登录。

之后我打电话

const request = {
    scopes: ["User.Read"],
    account: accounts[0]
};

instance.acquireTokenSilent(request).then(response => {
    console.log(response.accessToken);
}

我在控制台内获取令牌,但在 jwt.io 上检查它时,出现无效签名错误。

我的 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"
};

现在我放弃了使用 React 生成有效令牌,也许有人知道我必须做什么来解决这个问题。

到 ASP.NET Core
我在 Program.cs 中添加了

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(options =>
            {
                builder.Configuration.Bind("AzureAd", options);
                options.Events = new JwtBearerEvents();
            }, options => { builder.Configuration.Bind("AzureAd", options); });

使用AzureAD / Microsoft进行身份验证。

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"
  }

因为我想知道至少 ASP.NET Core 是否做了它应该做的事情,所以我使用以下方法生成了一个新密钥:

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"

这给了我一个带有有效签名的密钥,但是在调用时(将[授权]添加到控制器后)

https://example.com/API/returnHelloWorld

使用令牌,我只是得到“Bearer error =“invalid_token””。

有人知道如何运行它,或者有一个我可以看的例子吗?

reactjs asp.net-core microsoft-graph-api msal-react
1个回答
0
投票

首先,当您不提供 Microsoft 身份平台使用的公钥时,在 jwt.io 上验证令牌时预计会出现“无效签名”错误。为了在服务器端代码中进行验证,您应该使用可以自动检索 Microsoft 公钥的库。您不需要在 jwt.io 上手动验证这些令牌,除非您还提供来自 Microsoft 众所周知的 URL (

https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration
) 的公钥。

您在

authority
中的
msalConfig
网址似乎不正确。
authority
URL 通常以您的租户 ID 或“组织”结尾,而不是
/oauth2/v2.0/token

authority: "https://login.microsoftonline.com/eace0000-0000-0000-0000-6dced0000bc",

appsettings.json:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "local.example.com",
  "TenantId": "eace0000-0000-0000-0000-6dced0000bc",
  "ClientId": "c0000d4e-0000-0000-0000-425000032721",
  "Audience": "api://c0000d4e-0000-0000-0000-425000032721",
  "CallbackPath": "/signin-oidc"
}

您的

loginRequest
范围正在尝试使用您的客户端应用程序 ID (
.default
) 上的
api://c0000d4e-.../.default
范围。对于获取用于 API 的令牌来说,此范围通常是正确的,请确保 API 配置为此范围。

更详细的内容可以参考这个文档:

https://learn.microsoft.com/en-us/entra/identity-platform/scenario-protected-web-api-app-configuration?tabs=aspnetcore

https://learn.microsoft.com/en-us/samples/azure-samples/ms-identity-ciam-javascript-tutorial/ms-identity-ciam-javascript-tutorial-1-call-api-react/

Azure 身份验证受众验证失败

© www.soinside.com 2019 - 2024. All rights reserved.