【问题标题】:asp.net core 3.1 + react authentication AzureDBasp.net core 3.1 + 反应认证 AzureDB
【发布时间】:2021-01-09 20:42:46
【问题描述】:

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

在客户端我使用了 msal 库版本 1.4,在服务器端我使用了 Microsoft.Identity.Web 的 nuget 包。 每次服务器端返回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 });

关于我在ConfigureServices的Startup.cs文件中添加的Asp.net core web api:

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

在我添加的配置方法中

            app.UseRouting();

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

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

【问题讨论】:

  • 使用jwt.ms 解析您的令牌并提供屏幕截图。您必须确保客户端应用程序请求的范围与令牌的预期接收者一致。检查你的‘aud’,确保是你要调用的api,以及401的原因你可能使用了错误的token或者你使用了不属于该api的token来调用api。跨度>

标签: authentication azure-active-directory asp.net-core-webapi single-page-application asp.net-core-3.1


【解决方案1】:

您正在请求 Microsoft Graph (User.Read) 的范围。您需要为您的 web 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.中详述的步骤进行操作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多