ASP.NET Core Authentication With JWT – Part 1

Introduction

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

https://jwt.io/introduction/

SON Web Tokens consist of three parts separated by dots (.), which are:

  • Header: JSON object encoded in based64 format.
  • Payload: JavaScript object encoded in based64 format. It contains information about logged in user.
  • Signature: Digital signature generated by combining header and payload and based on secret key known to server.

Example: xxxxx.yyyyy.zzzzz

Project Configuration

We are going to implement JWT on .NET Core Web API. You can create a basic web API with template following this tutorial:

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio

Tutorial: Create a web API with ASP.NET Core by Microsoft

For implementing JWT we are going to modify startup class. We are going to create authentication wrapper for JWT.

To start we need to get

Microsoft.AspNetCore.Authentication.JwtBearer

https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer

from nuget package.

One good practice to keep your startup class clean and readable to use Extension class and create your Extension methods.

public static void ConfigureAuthentication(this IServiceCollection services)
        {
            services.AddAuthentication(opt => {
                    opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "http://localhost:5000",
                        ValidAudience = "http://localhost:5000",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySecretKey@2020"))
                    };
                });
        }

In this method we have register JWT authentication and specify authentication scheme and ChallengeScheme.

For more information visit:

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-3.1

Based on our configuration token would be valid if:

  1. Issuer must be the server that create the token.
  2. Valid recipient
  3. Token still valid and not expired
  4. Server trust the signing key

Based on the nature of your project you may need to support multiple authentication schemes. For example you may use Database and Azure active directory. In this cases your application should accept a JWT token from several issuers.

Example:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Audience = "https://localhost:5000/";
options.Authority = "https://localhost:5000/identity/";
})
.AddJwtBearer("AzureAD", options =>
{
options.Audience = "https://localhost:5000/";
options.Authority = "https://login.microsoftonline.com/eb971100-6f99-4bdc-8611-1bc8edd7f436/";
});

Next step is to make Authentication available for the application.

app.UseAuthentication()

Securing API Endpoint

In order to secure your API end points by decorating the action methods with the:

[Authorize]

You can secure by adding decoration at the controller level or at the action level. When you add the decoration at controller level, all actions inside the controller will be accessible if pass the authentication.

References:

Authorize with a specific scheme in ASP.N

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-3.1ET Core

Code-maze: https://code-maze.com/authentication-aspnetcore-jwt-1/

JWT: https://jwt.io/

Leave a Comment

Your email address will not be published. Required fields are marked *