问题描述
我使用 .NET Core 2-3 和 EF Identity cookie 身份验证,我需要能够将任何给定用户从他们登录的所有浏览“会话”中注销。
为此,我使用以下授权过滤器使 cookie“无效”:
public class CookieIsValidRequirementHandler : AuthorizationHandler<CookieIsValidRequirement>
{
private readonly ILogger _logger;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IHttpContextAccessor _httpContextAccessor;
public CookieIsValidRequirementHandler(
ILogger<CookieIsValidRequirementHandler> logger,SignInManager<IdentityUser> signInManager,IHttpContextAccessor httpContextAccessor
) {
_logger = logger;
_signInManager = signInManager;
_httpContextAccessor = httpContextAccessor;
}
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context,CookieIsValidRequirement requirement)
{
_logger.LogDebug("Checking if cookie is valid...");
Claim userIdClaim = context.User.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim == null || string.IsNullOrWhiteSpace(userIdClaim.Value))
{
_logger.LogDebug($"NameIdentifier Claim not found");
context.Succeed(requirement); // This is needed to allow the home page to load
return;
}
else
{
if (requirement.userIdsTologout.Contains(userIdClaim.Value))
{
_logger.Loginformation("Cookie is invalid! Logging user out!");
await _signInManager.SignOutAsync();
requirement.userIdsTologout.Remove(userIdClaim.Value);
_logger.Loginformation($"CAN I USE THIS??? {_httpContextAccessor.HttpContext}");
}
else
{
_logger.LogDebug("Cookie is valid!");
context.Succeed(requirement);
}
}
}
https://localhost:5001/Identity/Account/Login?ReturnUrl=%2FIdentity%2FAccount%2FAccessDenied%3FReturnUrl%3D%252F
我喜欢它将它们重定向到登录页面,但请注意 ReturnUrl 是访问被拒绝页面。我不想那样。
我尝试查看此处的黑匣子:https://github.com/dotnet/aspnetcore
看起来身份验证模型与使用启动类中可用的少量选项“配置”的“方案”紧密相关。
解决方法
不知道如果我理解正确,您可以在启动文件中的ConfigureServices方法中配置登录和拒绝访问路径。
示例:
services.AddAuthentication()
// cookies
.AddCookie(options =>{
options.LoginPath = "/Account/login";
options.AccessDeniedPath = "/Account/login";
});