Asp.net web api 如何允许特定角色使用identityserver3.accesstokenvalidation访问API
我有一个Identityserver4,它向客户端提供访问令牌 在我的API上,我希望在授予此用户访问API的权限之前,确保允许客户端访问特定范围,并且该用户属于特定角色 为此,我使用Identityserver3.accesstokenvalidation包Asp.net web api 如何允许特定角色使用identityserver3.accesstokenvalidation访问API,asp.net-web-api,identityserver3,Asp.net Web Api,Identityserver3,我有一个Identityserver4,它向客户端提供访问令牌 在我的API上,我希望在授予此用户访问API的权限之前,确保允许客户端访问特定范围,并且该用户属于特定角色 为此,我使用Identityserver3.accesstokenvalidation包 app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions {
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "Authority",
RequiredScopes = new[] { "MyScope" },
});
这会阻止没有访问令牌的用户访问我的API,同时还会检查提供的作用域是否为“MyScope”
我的问题是,在允许访问API之前,如何检查用户是否具有特定角色。您可以为特定控制器设置属性
[Authorize(Roles=“Admin”)]
。如果您需要更高级的声明逻辑,则需要指定您自己的属性,例如AuthorizePermissionAttribute
,并将其与控制器一起使用[AuthorizePermission(“预览”)]
:
public class AuthorizePermissionAttribute : AuthorizeAttribute
{
private readonly string grantedPermission;
public AuthorizePermissionAttribute(string permission)
{
this.grantedPermission = permission ?? throw new ArgumentNullException(nameof(permission));
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var claims = actionContext.ControllerContext.RequestContext.Principal as ClaimsPrincipal;
var permission = claims?.FindFirst(this.grantedPermission);
return permission != null && Convert.ToBoolean(permission.Value);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "insufficient_permissions");
actionContext.Response = response;
}
}
您还需要在Startup.cs中输入:
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["IdentityProviderApi"],
PreserveAccessToken = true
});
JwtSecurityTokenHandler.InboundClaimTypeMap=new Dictionary();
应用程序.使用IdentityServerBearTokenauthentication(新的IdentityServerBearTokenauthentication选项
{
Authority=ConfigurationManager.AppSettings[“IdentityProviderApi”],
PreserveAccessToken=true
});
没有JwtSecurityTokenHandler。InboundClaimTypeMap将始终返回未经授权的状态代码。谢谢您的回答,控制器如何理解它应该使用此类检查角色?什么是[授权许可(“预览”)?您可以添加一些解释吗?您可以为要保护的控制器添加[Authorize(Roles=“Admin”)(此逻辑来自.NET的AuthorizeAttribute)。[AuthorizePermission(“Preview”)]仅举一个示例,如果您需要更高级的逻辑,例如检查权限,如何使用您自己的属性。I c,谢谢。。我已经使用了[Authorize(Roles=“Admin”)],但它阻止了所有请求,即使访问令牌包含role:Admin as user claimI更新的答案,请注意InboundClaimTypeMap。