身份服务器4从webApi应用中的token获取角色



我已经正确配置了身份服务器4,它授权web api进行方法访问。但是,我不能在web api中使用角色,角色在令牌中,但是当它到达web api时,它没有给我进入api的授权。

IDS4配置

new Client
{
ClientId = "spaclient",
ClientName = "SPA Client",
RequireConsent = false,
AllowedGrantTypes =  GrantTypes.ResourceOwnerPassword,
RequirePkce = true,
RequireClientSecret = false,
AllowAccessTokensViaBrowser = true,
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"role" 
}
}
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("spaclient", "SPA")
};
public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("spaclient", "SPA")
};
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource("role","User Role", new List<string>() { "role" })
};
客户机配置

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:9002";  // --> IdentityServer Project
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
NameClaimType = "role",
RoleClaimType = "role"
};
});

控制器部分
[HttpGet]
[Authorize(Roles ="Administrator")] // <-- with role not work
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

[HttpGet]
[Authorize]<-- without role work fine
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

在您的访问令牌中没有角色声明。您需要配置现有的ApiScope或ApiResource,以包含必要的角色声明。

您所做的只是将它包含在您的ID-token中。

查看我在这里关于IdentityServer中各种资源类型之间关系的回答

在APIScope中添加一个用户声明,如下所示:
new ApiScope(name: "spaclient",
displayName:"SPA",
userClaims: new List<string>{ "role" }),

还必须请求空间客户端openid

控制令牌生存期:

var client2 = new Client
{
ClientId = "authcodeflowclient", 

IdentityTokenLifetime = 300,               //5 minutes
AccessTokenLifetime = 3600,                //1 hour
AuthorizationCodeLifetime = 300,           //5 minutes
AbsoluteRefreshTokenLifetime = 2592000,    //30 days
SlidingRefreshTokenLifetime = 1296000,     //15 days
...

为了补充这个答案,我写了一篇博客文章,更详细地讨论了这个话题:IdentityServer - IdentityResource与ApiResource与ApiScope

最新更新