从令牌中获取角色

时间:2021-07-23 16:25:51

标签: oauth-2.0 jwt bearer-token

我正在尝试从 azure 网络令牌验证角色类型。这是我的授权政策。

services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o => {
                o.Authority = Configuration["Identity:Authority"];
                o.RequireHttpsMetadata = false;
            });


services.AddAuthorization(options => {
                options.AddPolicy("ApiAccess", policy => {
                    policy.RequireClaim(System.Security.Claims.ClaimTypes.Role, "apiAccess");
                });
});

我可以在令牌中看到,前提是其中包含具有我的角色类型的角色。但是,如果我尝试访问我的网络应用程序中的任何页面,则表明我的角色不正确。

"roles": [
        "apiAccess"
    ],

1 个答案:

答案 0 :(得分:0)

您确定 System.Security.Claims.ClaimTypes.Role 解析为 roles 吗?如果您直接使用 roles 字符串会怎样:

policy.RequireClaim("roles", "apiAccess");

还是改用 .RequireRole 方法?

policy.RequireRole("apiAccess")