一切都很好,除了当我调用Fail时。这时什么也不会发生,会显示空白屏幕。这是我的HandleRequirementAsync方法。我已经尝试过各种任务结果的值。我一直在像疯子一样搜索谷歌,但没有成功。希望有人能帮忙。
期望的结果:我想在失败时重定向到一个自定义页面,但如果不可能,至少能够重定向回登录页面。唯一似乎有任何影响的就是抛出异常。
启动中相关的注册代码:
var appSettings = Configuration.GetSection("AppSettings");
services.Configure<Models.AppSettings>(appSettings);
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("RoleAuth", policy => policy.Requirements.Add(new RolesRequirement(appSettings["AllowedGroups"])));
});
services.AddSingleton<IAuthorizationHandler, RoleAuthorizationHandler>();
还有授权类:
public class RolesRequirement : IAuthorizationRequirement
{
public RolesRequirement(string groups)
{
Groups = groups;
}
public string Groups { get; private set; }
}
public class RoleAuthorizationHandler : AuthorizationHandler<RolesRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesRequirement requirement)
{
if (!string.IsNullOrWhiteSpace(requirement.Groups))
{
Console.WriteLine(requirement.Groups);
var groups = requirement.Groups.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
//we could check for group membership here.... maybe???
foreach (var group in groups)
{
if (context.User.IsInRole(group))
{
context.Succeed(requirement);
return Task.FromResult(0);
}
}
}
else
{
context.Succeed(requirement);
}
context.Fail();
return Task.FromResult(0);
}
}
AccountController.AccessDenied()
方法中再次从HandleRequirementAsync()
调用相同的代码并从那里重定向。在您的情况下,您需要所需的组,这使得此任务变得困难(反射等)。将内容添加到HttpContext.Items
中不起作用,在到达AccessDenied()
之前会被清除...最后(甚至更丑陋的)一招是在某个地方有一个静态的Dictionary<User,something>
,在HandleRequirementAsync()
中添加条目,并在AccessDenied()
中再次删除它们。是的,如果有更好的方法,我也会对此进行投票... - Louis Somers