.Net combine JwtAuthentication and BasicAuthenticationFilter

Viewed 21

I would like to have my controller work with both a token and BasicAth. like user have the option to use one of the two authentication

currently I am not able to make it work with both, it either work with Jwt or basicAuth but not both options

If I have them both like below, none work. any idea how I can make it work with either

        [JwtAuthentication]
        [BasicAuthenticationFilter(false)]
1 Answers

You can do the following.

In Program.cs

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Custom";
})
.AddPolicyScheme("Custom", "Custom", options =>
{
    options.ForwardDefaultSelector = context =>
    {
        string authHeader = context.Request.Headers["Authorization"];
        if (authHeader != null && authHeader.StartsWith("Basic "))
        {
            return BasicAuth;
        }
        else
        {
            return JwtBearerDefaults.AuthenticationScheme;
        }
    };

})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    // your code for token validation parameters.
})
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>(BasicAuth, null);

In Controller

 [Authorize]
 [HttpGet(Name = "GetWeatherForecast")]
 public IEnumerable<WeatherForecast> Get(){}

and you would have to implement BasicAuthenticationHandler where you need to validate the username and password.

Hope it helps.

Related