首页 > 解决方案 > Azure B2C 身份验证(角度 + .net 核心 Web API) - 在不记名令牌中找不到范围或角色声明

问题描述

我尝试使用 MSAL-angular 和 Azure B2C 做一个 Angular 应用程序进行身份验证。我能够使用 Azure B2C 对 Angular 应用程序进行身份验证(我创建了一个 susi 流)并获取令牌,如下图所示

代币获取

所以我创建了一个.net core web api项目并修改了appsetting配置并使用以下代码启动:

appsetting.json :

    "AzureAdB2C": {
    "Instance": "https://{mytenat}.b2clogin.com/tfp",
    "ClientId": "8xxxx-xxxx-xxxx-xxxx-xxxxxxxxc",
    "Domain": "{mytenat}.onmicrosoft.com",
    "SignUpSignInPolicyId": "B2C_1_susi"
  }

启动.cs

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApi(options =>
                    {
                        Configuration.Bind("AzureAdB2C", options);
                        options.TokenValidationParameters.RoleClaimType = "roles";
                        options.TokenValidationParameters.NameClaimType = "name";
                    },
                    options => { Configuration.Bind("AzureAdB2C", options); });

            // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
            //'http://schemas.microsodt.com/ws/2008/06/identity/clains/role' instead of 'roles'
            // This flag ensures that the ClaimsIdentity claims collection will be build from the claims in the token
            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
            //services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
            //{
            //    // The claim in the Jwt token where App roles are available.
            //    options.TokenValidationParameters.RoleClaimType = "roles";
            //});

但是如果我尝试在本地运行项目并用邮递员调用它,我会遇到这个错误:

**System.UnauthorizedAccessException:IDW10201:在不记名令牌中找不到范围或角色声明。**

我不明白错误在哪里。你能帮助我吗?

谢谢

标签: c#angularazureasp.net-coreazure-ad-b2c

解决方案


在您的问题中,您已在 Azure AD B2C 中创建了一个 Web api 应用程序和 Angular 应用程序。接下来需要暴露web api应用的api,然后给angular app添加权限。

首先去web api。

在此处输入图像描述

然后转到 Angular 应用程序>API 权限> 添加权限>我的 API>您的 Web api 应用程序。

在此处输入图像描述

最后,当您解析令牌时,您将看到scp:access声明。


推荐阅读