autheticate.fail 无法重定向到取消授权 asp.net 核心身份验证

autheticate.fail not able to redirect to unauthorize asp.net core authentication

在我的应用程序中启用 windows 身份验证

下面是我的处理程序代码

public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private readonly IUser _userService;
        public BasicAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock,
            IUser UserService
            ) : base(options, logger, encoder, clock)
        {
            _userService = UserService;
        }
        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var a = Request.HttpContext.User.Identity.Name;

            User user = null;
            user = await _userService.IsAuthenicated(a, "");
            // Context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            // Context.res = new RedirectToActionResult("Index", "Home", null);
            //Context.Response.StatusCode = StatusCodes.Status401Unauthorized;

            if (user == null)
            {

                return AuthenticateResult.Fail("Invalid Username or Password");
            }
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier,user.UserName),
                new Claim(ClaimTypes.Name, user.UserName),
            };

            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);


            return AuthenticateResult.Success(ticket);
        }
    }

autheticateresult.fail 循环请求 windows 凭据而不重定向到自定义错误页面。 当我尝试使用 anomyouns 时,它工作正常。

autheticateresult.fail make a loop ask for windows credential and not redirect to custom error page

当调用AuthenticateResult.Fail时,会使Windows Authentication失败,IIS会循环检查身份验证。

对于解决方法,您可以尝试 UseStatusCodePages 重定向到错误页面,

        app.UseStatusCodePages(async context => {
            if (context.HttpContext.Response.StatusCode == 401)
            {
                // your redirect
                context.HttpContext.Response.Redirect("/Home/Error");
            }
        });
        app.UseAuthentication();

对于另一种选择,您可以为 BasicAuthenticationHandler 自定义 HandleChallengeAsync

public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public BasicAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock
        ) : base(options, logger, encoder, clock)
    {
    }
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return AuthenticateResult.Fail("Invalid Username or Password");
    }

    protected override Task HandleChallengeAsync(AuthenticationProperties properties)
    {
        Context.Response.Redirect("/Home/Error");// redirect to your error page
        return Task.CompletedTask;
    }
}