Home > Mobile >  Mixed JWT and windows authentication. Credentials popup after jwt failed
Mixed JWT and windows authentication. Credentials popup after jwt failed

Time:10-15

I want to use JWT and Windows authentication on IIS. On IIS I enabled Windows and Anonymous authorization. I configured custom jwt auth:

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddScheme<BearerAuthenticationSchemeOptions, BearerAuthenticationHandler>(JwtBearerDefaults.AuthenticationScheme, null);
public class BearerAuthenticationHandler
    : AuthenticationHandler<BearerAuthenticationSchemeOptions>
{
    private IJwtUtils _jwtUtils;
    public BearerAuthenticationHandler(
        IOptionsMonitor<BearerAuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock,
        IJwtUtils jwtUtils)
        : base(options, logger, encoder, clock)
    {
        _jwtUtils = jwtUtils;
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        //if (HasAnonymousAttribute())
        //{
        //    return Task.FromResult(AuthenticateResult.NoResult());
        //}

        var token = Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
        var user = _jwtUtils.ValidateJwtToken(token);

        if (user != null)
        {
            var ticket = new AuthenticationTicket(user, this.Scheme.Name);
            return AuthenticateResult.Success(ticket);
        }


        return AuthenticateResult.NoResult(); 
    }
}

I marked the method in the controller with the attribute:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

And I added auth and autorization middlewares:

app.UseAuthentication();
app.UseAuthorization();

But after I returned AuthenticateResult.NoResult() the HandleAuthenticateAsync method is called again. And after that pop up Windows authorization.
I was expecting the 401 code to just come back.

Why is Windows authorization called after JWT?
How do I get a 401 after the JWT authorization fails?

CodePudding user response:

According to this issue, you could find the PG has replied:

This may not be possible in IIS. IIS will add Windows Auth challenges to any response with a 401 status code, triggering the login prompt. This happens outside of ASP.NET and your application, you don't have much control at that point.It should work with HttpSysServer because it's all controlled in process.

So you should not return 401 when the jwt failed. You should return other status codes and it will not trigger the login prompt like 600.

  • Related