ASP.NET Core 2.0 从 AuthorizationHandler、HandleRequirementAsync 方法重定向用户

ASP.NET Core 2.0 Redirecting user from AuthorizationHandler, HandleRequirementAsync method

我正在尝试在 .net core 2.0 中实现 AuthorizationHandler,我需要在其中对用户进行授权,并根据需要重定向到我的应用程序中的不同操作方法的条件验证工作正常,但我如何将用户重定向到 Access授权失败时拒绝或登录页面。

 protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasPermissionRequirement requirement)
    {
        var controllerContext = context.Resource as AuthorizationFilterContext;

        if (sessionManager.Session.sysUserID <= 0)
        {
            controllerContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login", area = "" }));

            return Task.FromResult(0);
        }


            if (Utilities.GetInt32Negative(PermissionID) == 1 || Utilities.GetInt32Negative(PermissionID) == -1)
            {
                if (!PagePath.Equals("~/"))
                    controllerContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "NoAccess", area = "" }));
            }

            context.Succeed(requirement);
        }
        else
        {
            if (!PagePath.Equals("~/"))
                controllerContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "NoAccess", area = "" }));
        }

        return Task.FromResult(0);
    }

首先,您可以通过创建自定义方案来配置登录条件 page/authentication。

public class SampleScheme : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string SchemeName = "sample";

    public SampleScheme(IOptionsMonitor<AuthenticationSchemeOptions> options, 
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) 
                    : base(options, logger, encoder, clock)
    {
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (myconditions){
            return AuthenticateResult.Fail("error message");
        }
        else {
            return await Context.AuthenticateAsync
            (CookieAuthenticationDefaults.AuthenticationScheme); 
           // return default cookie functionality. 
        }
    }

}

然后您也可以为 Access denied/forbidden 访问创建一个类似的 class(比方说 SampleScheme2)。 最后,您可以在 startup.cs

中设置它们
services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = SampleScheme.SchemeName;
    options.DefaultForbidScheme = SampleScheme2.SchemeName;
})
.AddCookie(options => {
    options.LoginPath = "/login";
    options.AccessDeniedPath = "/forbidden";
})
.AddScheme<AuthenticationSchemeOptions, SampleScheme>(SampleScheme.SchemeName, o => { });
.AddScheme<AuthenticationSchemeOptions, SampleScheme2>(SampleScheme2.SchemeName, o => { });

我希望代码能够自我解释。有一些变化,所以如果这不是您想要的,请告诉我。

我找到了解决方案,希望这能帮助寻找类似解决方案的人,在自定义授权中,我们可以使用 AuthorizationFilterContextRedirectToActionResult

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasPermissionRequirement requirement)
{
    // Get the context       
    var redirectContext = context.Resource as AuthorizationFilterContext;
    //check the condition 
    if (!result)
    {
        redirectContext.Result = new RedirectToActionResult("AccessDenied", "Home", null);
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
    context.Succeed(requirement);
    return Task.CompletedTask;
}