我使用 Azure AD 在我的 .Net core 3.1 webapi 中尝试了基于角色的授权。仅当我在 Authorize 属性中指定 Policy 或 Role 时才会出现此问题:
[Authorize(Policy = "p-web-api-with-roles-user")]
[Authorize(Roles="User")]
我的控制器:
[Authorize(Policy = "p-web-api-with-roles-user")]
public class BaseController : ControllerBase
startup.cs 中的配置服务:
services.AddAuthentication(rootOptions =>
{
rootOptions.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
rootOptions.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
})
.AddJwtBearer("AzureAD", options =>
{
options.Audience = configuration.GetValue<string>("Authentication:AzureAd:Audience");
options.Authority = configuration.GetValue<string>("Authentication:AzureAd:Instance") +
configuration.GetValue<string>("Authentication:AzureAd:TenantId");
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = configuration.GetValue<string>("Authentication:AzureAd:Issuer"),
ValidAudience = configuration.GetValue<string>("Authentication:AzureAd:Audience"),
RoleClaimType = "roles",
NameClaimType = "name"
};
});
services.AddAuthorization(policies =>
{
policies.AddPolicy("p-web-api-with-roles-user", p =>
{
p.RequireClaim("roles", "User");
});
policies.AddPolicy("p-web-api-with-roles-admin", p =>
{
p.RequireClaim("roles", "Admin");
});
});
我的 JWT 如下所示:
{
"aud": "f9ea4dcd-50f9-4bba-93ef-6514be396e98",
"iss": "https://login.microsoftonline.com/b4f51282-6eb2-4a8b-ae76-6632f8c4936a/v2.0",
"iat": 1643822217,
"nbf": 1643822217,
"exp": 1643826117,
"aio": "AZQAa/8TAAAAOt6II6GXwVFVT8flEfLQBtBoG2nknE+AX4UCIYqyyXSxPw0Go6kECzgwaILMsxs4hgZBiiYz+Ovt6GzkrCAvA64tqYOEhlPbSjCk2+n/J84MTxS7OsdxWIrpRNzvCDTihvLfkxL7zBU9UU5069Dxgnj2dkBgqlI06g0YAvGrTHfLei3ym5iEe8NpUIsnBhBX",
"idp": "https://sts.windows.net/cc994933-7128-4222-9d36-3e7f4fd81608/",
"name": "Abhilash CR",
"nonce": "8ce4cb72-f322-46a6-937c-d526fc2be1f1",
"oid": "aefdda8f-f83f-4ace-8316-4e47d82c0d27",
"preferred_username": "abhilash.cr@xyz.com",
"rh": "0.AQ0AghL1tLJui0qudmYy-MSTas1N6vn5ULpLk-9lFL45bpgNAEk.",
"roles": [
"User"
],
"sub": "B5soMutWa-fYNNShKCKA2QmNYi555yzTGGSScuMMfKg",
"tid": "b4f51282-6eb2-4a8b-ae76-6632f8c4936a",
"uti": "lazPqCkyIEioN0MHpycgAA",
"ver": "2.0"
}
我不确定我在这里犯了什么错误。简单地保留 [Authorize] 属性并不能验证角色。我想验证角色。