find and solve || findandsolve.com
Please wait.....

Welcome back.






Before Read Terms of use

JWT Authentication In ASP.NET Core

 

JWT (JSON Web Token) Authentication In ASP.NET Core

 

                                                           JWT means JSON Web Token this is a compact URL-safe means of representing   claims to be transferred between two parties.The claims in a JWT  are encoded as a JSON object,used as the payload of a JWT structure or plaintext JWE[JSON Wen Encryption ].It is digitally signed information is trusted and verified.It can be signed using private/public key ( RAS or ECDSA ) or made secret with HMAC algorithm. 
 

Structure of JWT
There are consists of three parts.


1. Header

         It is  typically consists of two parts
           i.  Type of the token  , which is JWT  
           ii. The signing algorithm being used, such as HMAC SHA256 or RSA.   
  For example:

    {
         "alg": "HS256",
         "typ": "JWT"
   }
The first part of the JWT is Base64Url encoded JSON.
 

2. Payload

                     The payload is the second part of token,which contains the claims. Statements about an entity (typically, the user) and additional data are Claims.There are theree types of Claims given below .


⦁    Registered claims : predefined claims,not this type of claims mandatory but recommended, to provide a set of useful.
⦁    Public claims: Public claims can be defined at will by those using JWTs.
⦁    Private claims :Private claims is the custom claims which is created to share information between parties that agree on using them and are neither registered or public claims.
 

For example:

{
  "sub": "984571520",
  "name": "rahul sharma",
  "superAdmin": true
}

The second part of the JWT is Base64Url encoded JSON.
 

3. Signature


         To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
 

For example:
 

HMACSHA256(

  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

There are separated by the dots(.).So JWT looks like "aaaaaaaaaa.bbbbbbbb.ccccccc"
 

Setup JWT with ASP.NET core web application
 


  Create an application using Visual Studio or using Command Line Interface (CLI).
dotnet new webapi -n JWTAuthentication  

 

This command will create an ASP.NET Web API project with name "JWTAuthentication" in the current folder.Configure JWT based authentication in our project first.you need to register a JWT authentication schema by using "AddAuthentication" method and specifying JwtBearerDefaults.AuthenticationScheme. Configure the authentication schema with JWT bearer options given below.public void

ConfigureServices(IServiceCollection services)  
{  
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  
    .AddJwtBearer(options =>  
    {  
        options.TokenValidationParameters = new TokenValidationParameters  
        {  
            ValidateIssuer = true,  
            ValidateAudience = true,  
            ValidateLifetime = true,  
            ValidateIssuerSigningKey = true,  
            ValidIssuer = Configuration["Jwt:Issuer"],  
            ValidAudience = Configuration["Jwt:Issuer"],  
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))  
        };  
    });  
    services.AddMvc();  
}  

 

The following items consider a token valid:
 

1.Validate the server (ValidateIssuer = true) that generates the token.
2.Validate the recipient of token is authorized to receive (ValidateAudience = true)
3.Check if token is not expired and the signing key of the issuer is valid (ValidateLifetime = true)
4.Validate signature of the token (ValidateIssuerSigningKey = true)
5.Additionally, we specify the values for the issuer, audience, signing key. In this example, I have stored these values in appsettings.json file.
 

 

AppSetting.Json
 

{  
  "Jwt": {  
    "Key": "findandsolvejwtkey",  
    "Issuer": "demo.com"  
  }  
}  
 

 

The next step, make the authentication service is available to the application.call app.UseAuthentication() method in the Configure method of startup class.cs.The UseAuthentication method is called before UseMvc method given below.
 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
{  
    app.UseAuthentication();       app.UseMvc();   }
 

Generate JSON Web Token
Created a LoginController and Login method within this controller, that is responsible to generate the JWT given below.

 
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JWTAuthentication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : Controller
    {
        private IConfiguration _config;
        public LoginController(IConfiguration config)
        {
            _config = config;
        }
        [AllowAnonymous]
        [HttpPost]
        [HttpPost]
        [HttpPost]
        public IActionResult Login([FromBody]UserViewModel login)
        {
            IActionResult response = Unauthorized();
            var user = AuthenticateUser(login);
            if (user != null)
            {
                var tokenString = JSONWebToken(user);
                response = Ok(new { token = tokenString });
            }
            return response;
        }
        private string JSONWebToken(UserViewModel userInfo)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
              _config["Jwt:Issuer"],
              null,
              expires: DateTime.Now.AddMinutes(30),
              signingCredentials: credentials);
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
        private UserViewModel AuthenticateUser(UserViewModel login)
        {
            UserViewModel user = null;
            //Validate the User Credentials  
            //Demo Purpose, This is  HardCoded User Information  you can use here dynamically data
            //Demo Purpose, This is  HardCoded User Information  you can use here dynamically data
            //Demo Purpose, This is  HardCoded User Information  you can use here dynamically data
            if (login.Username == "devin")
            {
                user = new UserViewModel { Username = "devin bhatta", EmailAddress = "demo.info@gmail.com" };
            }
            return user;
        }
    }
}

using Microsoft.AspNetCore.Authorization;
 

Conclusion

JSON Web Token is very famous in web developement. JWT is an open standard and JWT allows transmitting data between parties as a JSON object in a secure and compact way.In the artical,We will learn how to generate token using JWT and how to  use JWT with ASP.NET core application.

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response