中绕过发布版本的授权属性

中绕过发布版本的授权属性

本文介绍了在 .Net Core 中绕过发布版本的授权属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

有没有办法在asp.net核心中绕过"授权?我注意到 Authorize 属性不再有 AuthorizeCore 方法,您可以使用它来决定是否继续进行身份验证.

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 中的身份验证工作流程会很好.我只是无法为 .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 中绕过发布版本的授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:33