I need to support two authentication types in ASP.NET Core 2.0 MVC application:
- AddIdentityServerAuthentication
- AddOpenIdConnect
It was very easy in ASP.NET Core 1.0 version. But in version 2.0 version syntax changed. This is my code:
services.AddAuthentication(o =>
{
o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
o.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(options =>
{
options.Authority = PlatformConfiguration.IdentityServerUri;
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.ApiSecret = "somesecret";
options.ApiName = "some_api";
})
.AddCookie()
.AddOpenIdConnect(o =>
{
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.Authority = PlatformConfiguration.IdentityServerUri;
o.RequireHttpsMetadata = false;
o.ClientId = "some_viewer";
o.UseTokenLifetime = true;
o.ResponseType = "id_token token";
o.Scope.Add("openid");
o.Scope.Add("roles");
o.Scope.Add("profile");
o.SaveTokens = true;
o.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role
};
});
services.AddAuthorization();
But in this way, the Bearer authentication doesn't work. Because of default schemes: DefaultChallengeScheme, DefaultAuthenticateScheme.
How to define several authentication schemes?
Here is an example that I used to authenticate web pages using JWT token in ASP.NET 2.0
You can find the syntax I used even if it does not include all your needs I hope it will help you.
Asp Net Core
First step is write the method that configure Jwt authentication:
Now inside the ConfigureServices() method of the Startup.cs, we can call ConfigureJwtAuthService() method to configure the Jwt authentication.
This is the complete Startup.cs:
The JwtController.cs
On my project I use Angular. For call JwtController method by Angular:
On the controllers classes (or methods) that you want to be accessible only by authenticated users (not on your JwtController because its method must be accessible by all users) you can set:
To call from Angular the controller method that require authentication, you need to attach the token into the header with the getAuthHeader() method.
I hope this post can help you.
I've added attribute
And now I have two authentication schemes.
More flexible solution to use this code in Startup: