JWT Authentication In ASP.NET Core

JWT Authentication In ASP.NET Core
JWT Authentication In ASP.NET Core

JWT (JSON web token) has end up greater and extra famous in internet development. It is an open widespread which lets in transmitting data between events as a JSON object in a invulnerable and compact way. The records transmitting the usage of JWT between events are digitally signed so that it can be without problems tested and trusted.

In this article, we will study how to setup JWT with ASP.NET core internet application. We can create an software the use of Visual Studio or the usage of CLI (Command Line Interface).

dotnet new webapi -n JWTAuthentication   

Above command will create an ASP.NET Web API assignment with the title “JWTAuthentication” in the current folder.

The first step is to configure JWT primarily based authentication in our project. To do this, we need to register a JWT authentication schema by way of the usage of “AddAuthentication” approach and specifying JwtBearerDefaults.AuthenticationScheme. Here, we configure the authentication schema with JWT bearer options.

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();    
}   

In this example, we have designated which parameters need to be taken into account to reflect onconsideration on JWT as valid. As per our code, the following gadgets reflect onconsideration on a token valid:

  • Validate the server (ValidateIssuer = true) that generates the token.
  • Validate the recipient of the token is licensed to obtain (ValidateAudience = true)
  • Check if the token is now not expired and the signing key of the provider is legitimate (ValidateLifetime = true)
  • Validate signature of the token (ValidateIssuerSigningKey = true)
  • Additionally, we specify the values for the issuer, audience, signing key. In this example, I have saved these values in appsettings.json file.

AppSetting.Json

{    
  "Jwt": {    
    "Key": "ThisismySecretKey",    
    "Issuer": "Test.com"    
  }    
}   

The above-mentioned steps are used to configure a JWT based totally authentication service. The subsequent step is to make the authentication provider is reachable to the application. To do this, we want to name app.UseAuthentication() technique in the Configure approach of startup class. The UseAuthentication technique is known as earlier than UseMvc method.

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

Generate JSON Web Token

I have created a LoginController and Login approach inside this controller, which is accountable to generate the JWT. I have marked this technique with the AllowAnonymous attribute to pass the authentication. This approach expects the Usermodel object for Username and Password.

I have created the “AuthenticateUser” method, which is accountable to validate the consumer credential and returns to the UserModel. For demo purposes, I have back the hardcode mannequin if the username is “Jignesh”. If the “AuthenticateUser” approach returns the consumer model, API generates the new token through the use of the “GenerateJSONWebToken” method.

Here, I have created a JWT the use of the JwtSecurityToken class. I have created an object of this type by means of passing some parameters to the constructor such as issuer, audience, expiration, and signature.

Finally, JwtSecurityTokenHandler.WriteToken approach is used to generate the JWT. This approach expects an object of the JwtSecurityToken class.

using Microsoft.AspNetCore.Authorization;    
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]    
        public IActionResult Login([FromBody]UserModel login)    
        {    
            IActionResult response = Unauthorized();    
            var user = AuthenticateUser(login);    
    
            if (user != null)    
            {    
                var tokenString = GenerateJSONWebToken(user);    
                response = Ok(new { token = tokenString });    
            }    
    
            return response;    
        }    
    
        private string GenerateJSONWebToken(UserModel 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(120),    
              signingCredentials: credentials);    
    
            return new JwtSecurityTokenHandler().WriteToken(token);    
        }    
    
        private UserModel AuthenticateUser(UserModel login)    
        {    
            UserModel user = null;    
    
            //Validate the User Credentials    
            //Demo Purpose, I have Passed HardCoded User Information    
            if (login.Username == "Jignesh")    
            {    
                user = new UserModel { Username = "Jignesh Trivedi", EmailAddress = "test.btest@gmail.com" };    
            }    
            return user;    
        }    
    }    
}   

Once, we have enabled the JWT based totally authentication, I have created a easy Web API approach that returns a listing of fee strings when invoked with an HTTP GET request. Here, I have marked this approach with the authorize attribute, so that this endpoint will set off the validation take a look at of the token handed with an HTTP request.

If we name this approach except a token, we will get 401 (UnAuthorizedAccess) HTTP fame code as a response. If we choose to pass the authentication for any method, we can mark that technique with the AllowAnonymous attribute.

To check the created Web API, I am Using Fiddler. First, I have requested to “API/login” technique to generate the token. I have handed the following JSON in the request body.

{"username": "Jignesh", "password": "password"}   
As a response, we will get the JSON like the following,
{    
    "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY"    
}  

Now, we will attempt to get the list of values through passing this token into the authentication HTTP header. Following is my Action approach definition.

[HttpGet]    
[Authorize]    
public ActionResult<IEnumerable<string>> Get()    
{    
    return new string[] { "value1", "value2", "value3", "value4", "value5" };    
}  
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY  

Handle Claims with JWT

Claims are information contained with the aid of the token. They are records about the person which helps us to authorize get entry to to a resource. They should be Username, e mail address, role, or any different information. We can add claims records to the JWT so that they are handy when checking for authorization.

In the above example, if we favor to ignore the claims to our token then the declare data desires to add GenerateJSONWebToken approach of Login controller. In the following example, I have brought a username, e-mail address, and date of becoming a member of as claimed into the token.

private string GenerateJSONWebToken(UserModel userInfo)    
{    
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));    
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);    
    
    var claims = new[] {    
        new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),    
        new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress),    
        new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),    
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())    
    };    
    
    var token = new JwtSecurityToken(_config["Jwt:Issuer"],    
        _config["Jwt:Issuer"],    
        claims,    
        expires: DateTime.Now.AddMinutes(120),    
        signingCredentials: credentials);    
    
    return new JwtSecurityTokenHandler().WriteToken(token);    
}   

The claims are an array of key-value pair. The keys might also be values of a JwtRegisteredClaimNames shape (it affords names for public standardized claims) or customized identify (such as DateOfJoining in above example).

This claims can be used to filter the data. In the following example, I have to trade the listing of values if the person spends extra than 5 years with the company.

[HttpGet]    
[Authorize]    
public ActionResult<IEnumerable<string>> Get()    
{    
    var currentUser = HttpContext.User;    
    int spendingTimeWithCompany = 0;    
    
    if (currentUser.HasClaim(c => c.Type == "DateOfJoing"))    
    {    
        DateTime date = DateTime.Parse(currentUser.Claims.FirstOrDefault(c => c.Type == "DateOfJoing").Value);    
        spendingTimeWithCompany = DateTime.Today.Year - date.Year;    
    }    
    
    if(spendingTimeWithCompany > 5)    
    {    
        return new string[] { "High Time1", "High Time2", "High Time3", "High Time4", "High Time5" };    
    }    
    else    
    {    
        return new string[] { "value1", "value2", "value3", "value4", "value5" };    
    }    
}   
Summary

JWT is very well-known in net development. It is an open popular that lets in transmitting facts between events as a JSON object in a invulnerable and compact way. In this article, we will study how to generate and use JWT with ASP.NET core application.

57 Shares:
Leave a Reply

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

fifteen + 5 =

You May Also Like
Twelve-Factor Application of Microservices
Read More

The Twelve-Factor App

Introduction In the current era, software program is usually delivered as a service: referred to as net apps,…