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 a
uthentication 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:
- Issuer must be the server that create the token.
- Valid recipient
- Token still valid and not expired
- 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
Code-maze: https://code-maze.com/authentication-aspnetcore-jwt-1/
JWT: https://jwt.io/
I really like it whenever people get together and share opinions. Great blog, stick with it. Isaiah Bhatt
Every the moment inside a whilst we pick out blogs that we study. Listed beneath would be the most current web sites that we decide on. Winston Tosic
Thanks again for the article. Much thanks again. Really Cool. Bennie Pell
This article presents clear idea in support of the new viewers of blogging, that in fact how to do blogging. Robby Maccarone
Just wanna tell that this is extremely helpful, Thanks for taking your time to write this. Aron Rougier
Hello mates, good post and good urging commented at this place, I am really enjoying by these. Marcelo Nairn
Really informative article. Really looking forward to read more. Fantastic. Jimmy Zirk
That is a good tip especially to those fresh to the blogosphere. Don Anderson