微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 ASP .NET Core 中更改 SignOutAsync ReturnUrl

如何解决如何在 ASP .NET Core 中更改 SignOutAsync ReturnUrl

我使用 .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";
            }); 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。