问题描述
在asp.net核心中是否有一种绕过"授权的方法?我注意到Authorize属性不再具有AuthorizeCore方法,您可以使用该方法来决定是否继续进行auth.
Is there a way to "bypass" authorization in asp.net core? I noticed that the Authorize attribute no longer has a AuthorizeCore method with which you could use to make decisions on whether or not to proceed with auth.
.net核心之前,您可以执行以下操作:
Pre .net core you could do something like this:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// no auth in debug mode please
#if DEBUG
return true;
#endif
return base.AuthorizeCore(httpContext);
}
我希望我不会错过任何明显的东西,但是如果需要的话,能够跳过DEBUG中的auth工作流会很好.我只是无法在.net core中找到它
I hope I'm not missing something blatantly obvious but it would be nice to be able to skip the auth workflow in DEBUG if needed. I just haven't been able to find it for .net core
推荐答案
正如注释中指出的,您可以为所有需求处理程序创建基类.
As pointed out in the comments, you can create a base class for all your requirement handlers.
public abstract class RequirementHandlerBase<T> : AuthorizationHandler<T> where T : IAuthorizationRequirement
{
protected sealed override Task HandleRequirementAsync(AuthorizationHandlerContext context, T requirement)
{
#if DEBUG
context.Succeed(requirement);
return Task.FromResult(true);
#else
return HandleAsync(context, requirement);
#endif
}
protected abstract Task HandleAsync(AuthorizationHandlerContext context, T requirement);
}
然后从该基类派生您的需求处理程序.
Then derive your requirement handlers from this base class.
public class AgeRequirementHandler : RequirementHandlerBase<AgeRequirement>
{
protected override HandleAsync(AuthorizationHandlerContext context, AgeRequirement requirement)
{
...
}
}
public class AgeRequirement : IRequrement
{
public int MinimumAge { get; set; }
}
然后只需注册即可.
services.AddAuthorization(options =>
{
options.AddPolicy("Over18",
policy => policy.Requirements.Add(new AgeRequirement { MinimumAge = 18 }));
});
这篇关于发行版.Net Core中的绕过授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!