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.
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.
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)
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With