6

I'm developing a web api core 2.0 project.

I need support two authorization types: jwt and basic.

Inside my ConfigureServices method I've added this code:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer((options) =>
{
    options.Authority = $"...";
    options.Audience = "...";
});

services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(credentials =>
Task.FromResult(
   credentials.username == "username"
   && credentials.password == "password"));

Inside my Configure method I've added this code:

app.UseAuthentication();
app.UseMvc();

And finally I've added AuthorizeAttribute on my controller:

[Authorize]
public class MioController : Controller
{ ... }

Actually work only the last authentication specified on ConfigureServices.

How can I support both authentication types? Thanks

Note: I'm using this NuGet package for basic authentication Bazinga.AspNetCore.Authentication.Basic.

1
  • Authorize attribute has related property: [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] Commented Mar 7, 2018 at 9:51

1 Answer 1

9

try Adding your authentication service in one chain

services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer((options) =>
{
    options.Authority = $"...";
    options.Audience = "...";
})
.AddBasicAuthentication(credentials =>
{
    Task.FromResult(credentials.username == "username" && credentials.password == "password"));
}

and also on AuthorizeAttribute you can specify which Scheme you want to authenticate the request with

[Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme + ", " + JwtBearerDefaults.AuthenticationScheme)]
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Kahbazi, I've implemented your suggestions but now work only authorization with bearer (jwt).
You need to use [Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme)] for basicAuthentication to authenticate. By default only JWT would authenticate each request
Hi Kahbazi, using BasicAuthenticationScheme i obtain the same problem but with basic authentication.
I've resolved using [Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme + ", " + JwtBearerDefaults.AuthenticationScheme)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.