我正在尝试在.net core 2.0中实现AuthorizationHandler,我需要授权用户并根据想要重定向到我的应用程序验证中的不同操作方法的条件正常工作,但我如何将用户重定向到Access Denied或授权失败时的登录页面。
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);
}
答案 0 :(得分:14)
我找到了解决方案,我希望这可以帮助那些寻找相似的自定义授权的人,我们可以使用 AuthorizationFilterContext 和 RedirectToActionResult
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;
}
答案 1 :(得分:1)
首先,您可以通过创建这样的自定义方案来配置登录页面/身份验证的条件。
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拒绝/禁止访问创建一个类似的类(比如说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 => { });
我希望代码足够自我解释。有一些变化,所以让我知道这是不是你想要的。