asp.net core 3.1 + react 认证 AzureDB

asp.net core 3.1 + react authentication AzureDB

我有一个包含 React 客户端和后端的 Asp.net 核心 3.1 web api 的应用程序,我尝试使用 AzureAD 添加身份验证,但现在只是为了验证不授权。

在客户端我使用了 msal 库版本 1.4,在服务器端我使用了 Microsoft.Identity.Web 的 nuget 包。 每次服务器端 returns 401 和日志都没有指示。

感谢您的帮助!我已经添加了日志和所有相关代码

[18:24:29 INF] Authorization failed.
[18:24:29 INF] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
[18:24:29 INF] Executing ChallengeResult with authentication schemes (["Bearer"]).
[18:24:29 INF] AuthenticationScheme: Bearer was challenged.
import { UserAgentApplication} from "msal";


let msalConfig = {
    auth: {
        clientId: "7e3d8e08-2b42-46a8-83c1-5167d636808e",
        redirectUri: "http://localhost:3000",
        authority: "https://login.microsoftonline.com/78820852-55fa-450b-908d-45c0d911e76b",
        navigateToLoginRequestUrl: false
    },
    cache: {
        cacheLocation: "localStorage",
        storeAuthStateInCookie: true
    }
}


var msalInstance = new UserAgentApplication(msalConfig);


export { msalInstance };

稍后在另一页中我有这个功能:

        const handleLoginClick = () => {
            const accessTokenRequest = {
                scopes: ["user.read"]
            }
            msalInstance.loginPopup(accessTokenRequest)
                .then(response => {
                    msalInstance.acquireTokenSilent(accessTokenRequest).then(tokenReponse => {
                            console.log(tokenReponse);
                            localStorage.setItem('token', tokenReponse.accessToken);
                            handleLoginSuccess();
                        });
                });
        }

最后在 axios get 请求中发送令牌:

var config = {
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Authorization': `Bearer` + token
        }
    };

    var response = await axios.get(`${SERVER_URL}/${API_Path}`, config, { timeout: 15000 });

在 Asp.net 核心网站上 api 我在 ConfigureServices 的 Startup.cs 文件中添加:

           services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration);

            services.AddControllers(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

配置:

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xxx.onmicrosoft.com",
    "TenantId": "xxxxx-xxxx-xxxx-xxx-xxxx",
    "ClientId": "xxxxx-xxxx-xxxx-xxx-xxxx",
  }

并且在我添加的Configure方法中

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

您正在请求 Microsoft Graph 的范围 (User.Read)。您需要为您的网站请求它们 api。按照 A React & Redux single-page application authorizing an ASP.NET Core Web API to call MS Graph API on behalf of a signed-in user.

中详述的步骤进行操作