本文介绍了根据策略列表授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理不同的应用程序,每个应用程序都有自己的角色成员。
在Startup.cs
var c= _configuration.GetSection(nameof(Configuration)).Get<List<Configuration>>();
foreach (Configuration r in c)
{
services.AddAuthorization(options => {
options.AddPolicy(Configuration.Role, policy =>
policy.RequireRole(r.RoleMembers.Split(",")));
});
}
下面的代码不起作用,因为我引用的是数组。
[Authorize(Policy = Configuration.Role)]
如何针对第0个元素进行授权?
推荐答案
您可以为多个策略实现自定义授权属性。
1.AuthorizeMultiplePolicyAttribute
public class AuthorizeMultiplePolicyAttribute : TypeFilterAttribute
{
public AuthorizeMultiplePolicyAttribute(string[] policies) : base(typeof(AuthorizeMultiplePolicyFilter))
{
Arguments = new object[] { policies };
}
}
2.AuthorizeMultiplePolicyFilter
public class AuthorizeMultiplePolicyFilter : IAsyncAuthorizationFilter
{
private readonly IAuthorizationService _authorization;
public string[] _policies { get; private set; }
public AuthorizeMultiplePolicyFilter(string[] policies,IAuthorizationService authorization)
{
_policies = policies;
_authorization = authorization;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
foreach (var policy in _policies)
{
var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy);
if (!authorized.Succeeded)
{
context.Result = new ForbidResult();
return;
}
}
}
}
3.逐个添加启动时需要的策略
services.AddAuthorization(options =>
{
//register all policies based on your own code,give them different policy name
options.AddPolicy("AdminPolicy", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("SuperPolicy", policy =>
policy.RequireRole("Super"));
});
4.使用自定义属性
[AuthorizeMultiplePolicy(new string[] { "AdminPolicy", "SuperPolicy" })]
这篇关于根据策略列表授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!