Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support multiple authentication scheme in Web API Core 2?

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.

like image 576
ilMattion Avatar asked Mar 07 '18 09:03

ilMattion


People also ask

How do I add authentication to Web API?

In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.

What are different authentication schemes?

Custom Authentication Schemes. OpenID Authentication Scheme. Legacy Federation Authentication Schemes. Impersonation Authentication Schemes. JSON Web Token (JWT) Authentication Scheme (Release 12.8 through 12.8.02)

How many types of authentication are there in asp net core?

This blog starts with authentication and authorization concepts and after that explains the three default important ways and three custom authentication ways for doing authentication and authorization i.e. windows, forms ,passport, multipass, JWT and SAML authentication.


1 Answers

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)]
like image 51
Kahbazi Avatar answered Nov 14 '22 23:11

Kahbazi