ASP.NET Core Token Authentication And Authorization Using JWT

These days JSON Web Token (JWT) has become more popular in web application development, it has a standard way of transmitting data between multiple parties.

What is JWT Token?

 
JSON Web Token is a JSON based access token which is signed by one private key or one party and the party will be able to verify the token. It is safe and compact. JWT is a JSON object that has the capacity to transmit information between multiple parties.
 
Its structure consists of  Header, Payload, and Signature.
 
The header contains two parts which are encoded by base64 format.
  1. {  
  2. "alg" : "HS256",  
  3. "typ" : "JWT"  
  4. }  
The payload is basic information that we wanted to send to the client, like login user information.
  1. {  
  2.  "name" : "admin",  
  3.  "code" : "adm12873",  
  4. }  
The signature is basically used for validating the message and another responsibility of signature is whether the token contains authentic information or not. The signature is encoded by Base64url Encoding.
  1. HMAC-SHA256(  
  2.     base64urlEncoding(header) + '.' +  
  3.     base64urlEncoding(payload),  
  4.     secret  
  5. )  

ASP.NET Core Token Authentication and Authorization using JWT

 
In ASP.NET Core controller handles all the HTTP requests/ routes and each route has been called by the client to perform the action required.
 
We need to secure the controller using JWT by [Authorize] attribute. That is why we need some configuration to register a JWT.
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  3.     var appSettingsSection = Configuration.GetSection("AppSettings");  
  4.     services.Configure < KeySettings > (appSettingsSection);  
  5.     var appSettings = appSettingsSection.Get < KeySettings > ();  
  6.     var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);  
  7.     services.AddAuthentication(x => {  
  8.         x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;  
  9.         x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;  
  10.     }).AddJwtBearer(x => {  
  11.         x.RequireHttpsMetadata = false;  
  12.         x.SaveToken = true;  
  13.         x.TokenValidationParameters = new TokenValidationParameters {  
  14.             ValidateIssuerSigningKey = true,  
  15.                 IssuerSigningKey = new SymmetricSecurityKey(key),  
  16.                 ValidateIssuer = false,  
  17.                 ValidateAudience = false  
  18.         };  
  19.     });  
  20.     services.AddScoped < IUserService, UserService > ();  
  21. }  
As we know, in appsettings.json configuration is kept by the form of key-value pairs. We need to provide a configuration for SecretKey.
  1. {  
  2.     "AppSettings": {  
  3.         "SecretKey""WQW79-OFFKDI940NG7-56753253-SADVF-5769-0921-DSD987987SA"  
  4.     },  
  5.     "Logging": {  
  6.         "LogLevel": {  
  7.             "Default""Warning"  
  8.         }  
  9.     }  
  10. }  
After application settings, we need to Configure User Authentication service by using app.UseAuthentication(). 
 
Startup.cs
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  2.     app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());  
  3.     app.UseAuthentication();  
  4.     app.UseMvc();  
  5. }  
In the above code, you can see the app.UseCors() method, we are using this method to Allow any Origin.  We will discuss what Cross-Origin Request (CORS) is later. 
 

How to Generate JSON Web Token in ASP.NET Core? 

 
Here I have introduced a JWTController. This Controller will invoke the IsValidate() method for user validation and that method will generate the JWT token, I have decorated my action methods [HttpPost("token")] and it allows an Anonymous call by using [AllowAnonymous] attribute.
  1. using JwtToken.Model;  
  2. using JwtToken.Services;  
  3. using Microsoft.AspNetCore.Authorization;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. namespace JwtToken.Controllers {  
  6.     [Authorize]  
  7.     public class JWTController: ControllerBase {  
  8.         IUserValidationService _uservalidationService;  
  9.         public JWTController(IUserValidationService uservalidationService) {  
  10.                 this._uservalidationService = uservalidationService;  
  11.             }  
  12.             [AllowAnonymous]  
  13.             [HttpPost("token")]  
  14.         public IActionResult Authenticate([FromBody] UserEntity userParam) {  
  15.             var user = this._uservalidationService.IsValidate(userParam.Username, userParam.Password);  
  16.             if (user == null) {  
  17.                 return BadRequest(new {  
  18.                     message = "UserName or Password is invalid"  
  19.                 });  
  20.             }  
  21.             return Ok(user);  
  22.         }  
  23.     }  
  24. }  
In here you can see the IsValidate() method that will validate and return JWT.
 
UserValidationService.cs
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.IdentityModel.Tokens.Jwt;    
  4. using System.Linq;    
  5. using System.Security.Claims;    
  6. using System.Text;    
  7. using JwtToken.HelperService;    
  8. using JwtToken.Model;    
  9. using Microsoft.Extensions.Options;    
  10. using Microsoft.IdentityModel.Tokens;    
  11. namespace JwtToken.Services {    
  12.     public class UserValidationService: IUserValidationService {    
  13.         List < UserEntity > users;    
  14.         KeySettings key;    
  15.         public UserValidationService(IOptions < KeySettings > appSettings) {    
  16.             this.key = appSettings.Value;    
  17.             this.users = new List < UserEntity > {    
  18.                 new UserEntity {    
  19.                     Id = 1, FirstName = "Sachin", LastName = "Tendulkar", Email = "sachin@gmail.com", Username = "sachin", Password = "123"    
  20.                 }    
  21.             };    
  22.         }    
  23.         public UserEntity IsValidate(string username, string password) {    
  24.             var user = users.SingleOrDefault(x => x.Username == username && x.Password == password);    
  25.             if (user == null) {    
  26.                 return null;    
  27.             }    
  28.             var key = Encoding.ASCII.GetBytes(this.key.SecretKey);    
  29.             var jwtToken = new SecurityTokenDescriptor {    
  30.                 Subject = new ClaimsIdentity(new Claim[] {    
  31.                         new Claim(ClaimTypes.Name, user.Id.ToString())    
  32.                     }),    
  33.                     Expires = DateTime.UtcNow.AddDays(10),    
  34.                     SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)    
  35.             };    
  36.             var tokenHandler = new JwtSecurityTokenHandler();    
  37.             var token = tokenHandler.CreateToken(jwtToken);    
  38.             user.Token = tokenHandler.WriteToken(token);    
  39.             return user;    
  40.         }    
  41.     }    
  42. }    
In the above section, I have used hardcode data to test the user authentication. Here I have introduced SecurityTokenDescriptor class to decorate JWT Token, Claim Expires, and SigningCredentials.
 

How to Test the API?

 
To test the Web API, I am Using PostMan and the following JSON in the request body.
 
https://localhost:44392/token
 
POST
 
Content-Type : application/json
  1. {  
  2.     "username""sachin",  
  3.     "password""123"  
  4. }  
ASP.NET Core Token Authentication And Authorization Using JWT
 
Based on the response, we will get the following JSON like.
  1. {  
  2.     "id": 1,  
  3.     "firstName""Sachin",  
  4.     "lastName""Tendulkar",  
  5.     "username""sachin",  
  6.     "password""123",  
  7.     "token""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjEiLCJuYmYiOjE1Njg5MjQ4NDQsImV4cCI6MTU2OTc4ODg0NCwiaWF0IjoxNTY4OTI0ODQ0fQ.YmXyHl4J-dY43nT96h-00E8Az7YWDECJon0ZLu6fjik",  
  8.     "email""sachin@gmail.com"  
  9. }  
Now I am going to validate other Controller to see if the JWT is working for me or not. In here we need to pass the JWT like this way.
 
ASP.NET Core Token Authentication And Authorization Using JWT
 

Conclusion

 
Authentication is the most essential part of any web application, specifically WEB API. Because your WEB API can consume any client. Microsoft has introduced OAuth 2.0 and the JSON Web Token (JWT). In this article, you learned about JWT as well as how to implement JWT by using ASP.NET Core.