我从ASP.Net Framework迁移到ASP.Net Core。
在带有Web API 2项目的ASP.Net Framework中,我可以像这样自定义AuthorizeAttribute:
public class ApiAuthorizeAttribute : AuthorizationFilterAttribute
{
#region Methods
/// <summary>
/// Override authorization event to do custom authorization.
/// </summary>
/// <param name="httpActionContext"></param>
public override void OnAuthorization(HttpActionContext httpActionContext)
{
// Retrieve email and password.
var accountEmail =
httpActionContext.Request.Headers.Where(
x =>
!string.IsNullOrEmpty(x.Key) &&
x.Key.Equals("Email"))
.Select(x => x.Value.FirstOrDefault())
.FirstOrDefault();
// Retrieve account password.
var accountPassword =
httpActionContext.Request.Headers.Where(
x =>
!string.IsNullOrEmpty(x.Key) &&
x.Key.Equals("Password"))
.Select(x => x.Value.FirstOrDefault()).FirstOrDefault();
// Account view model construction.
var filterAccountViewModel = new FilterAccountViewModel();
filterAccountViewModel.Email = accountEmail;
filterAccountViewModel.Password = accountPassword;
filterAccountViewModel.EmailComparision = TextComparision.Equal;
filterAccountViewModel.PasswordComparision = TextComparision.Equal;
// Find the account.
var account = RepositoryAccount.FindAccount(filterAccountViewModel);
// Account is not found.
if (account == null)
{
// Treat the account as unthorized.
httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
return;
}
// Role is not defined which means the request is allowed.
if (_roles == null)
return;
// Role is not allowed
if (!_roles.Any(x => x == account.Role))
{
// Treat the account as unthorized.
httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
// Store the requester information in action argument.
httpActionContext.ActionArguments["Account"] = account;
}
#endregion
#region Properties
/// <summary>
/// Repository which provides function to access account database.
/// </summary>
public IRepositoryAccount RepositoryAccount { get; set; }
/// <summary>
/// Which role can be allowed to access server.
/// </summary>
private readonly byte[] _roles;
#endregion
#region Constructor
/// <summary>
/// Initialize instance with default settings.
/// </summary>
public ApiAuthorizeAttribute()
{
}
/// <summary>
/// Initialize instance with allowed role.
/// </summary>
/// <param name="roles"></param>
public ApiAuthorizeAttribute(byte[] roles)
{
_roles = roles;
}
#endregion
}
在我的自定义AuthorizeAttribute中,我可以检查帐户是否有效,并将HttpStatusCode返回给客户端。
我试图在ASP.Net Core中做同样的事情,但我没有OnAuthorization来覆盖。
如何实现与ASP.Net Framework相同的功能?
谢谢,
答案 0 :(得分:11)
你正在接近这个错误。从来没有真正鼓励为此编写自定义属性或扩展现有属性。使用 ASP.NET Core 角色仍然是系统的一部分,用于向后兼容,但现在也不鼓励它们。
关于一些驱动架构的变化以及它应该被利用的方式有一个很好的2部分系列here。如果您仍然希望依赖角色,我建议您使用政策。
要连接策略,请执行以下操作:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy(nameof(Policy.Account),
policy => policy.Requirements.Add(new AccountRequirement()));
});
services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}
为方便起见,我创建了一个Policy
枚举。
public enum Policy { Account };
装饰入口点:
[
HttpPost,
Authorize(Policy = nameof(Policy.Account))
]
public async Task<IActionResult> PostSomething([FromRoute] blah)
{
}
AccountRequirement
只是占位符,需要实现IAuthorizationRequirement
界面。
public class AccountRequirement: IAuthorizationRequirement { }
现在我们只需要创建一个处理程序并将其连接到DI。
public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AccountRequirement requirement)
{
// Your logic here... or anything else you need to do.
if (context.User.IsInRole("fooBar"))
{
// Call 'Succeed' to mark current requirement as passed
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
其他资源
答案 1 :(得分:1)
我的评论作为评论看起来很糟糕,因此我发布了答案,但仅在使用MVC时有用:
// don't forget this
services.AddSingleton<IAuthorizationHandler, MyCustomAuthorizationHandler>();
services
.AddMvc(config => { var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser() .AddRequirements(new[] { new MyCustomRequirement() })
.Build(); config.Filters.Add(new AuthorizeFilter(policy)); })
我还注意到在问题代码中,异步关键字对于“ HandleRequirementAsync”签名是多余的。而且我想返回Task.CompletedTask可能会很好。