JWT Authentication In ASP.NET Core

JWT Authentication In ASP.NET Core

Learn how to setup JWT (JSON web token) with ASP.NET core internet application. We can create an software the use of Visual Studio or the usage of CLI (Command Line Interface). JWT 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.

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 = "[email protected]" };    
            }    
            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);    
}   

jwt aspdotnet security programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Best Custom Web & Mobile App Development Company

Top Web & Mobile Application Development Company in India & USA. We specialize in Golang, Ruby on Rails, Symfony, Laravel PHP, Python, Angular, Mobile Apps, Blockchain, & Chatbots

50+ Useful Kubernetes Tools for 2020 - Part 2

Our original Kubernetes tool list was so popular that we've curated another great list of tools to help you improve your functionality with the platform.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Developer Career Path: To Become a Team Lead or Stay a Developer?

For a developer, becoming a team leader can be a trap or open up opportunities for creating software. Two years ago, when I was a developer, ... by Oleg Sklyarov, Fullstack Developer at Skyeng company

Software Security Primer

As a developer, when you think of security, what comes to mind? Is it clear what are different aspects that need to be handled to make a software secure? And why you need to do that?