Token based Authentication in Web API

Token based Authentication in Web API

Token based Authentication in Web API

In this article, we will learn how to perform token-based authentication with JWT (JSON Web Token) in ASP.NET Core Web API.  JWT is a standard way to transmit data between two parties securely. JWT is generally signed by both parties so this easily trusted by both. JWT token mainly used in Web and Mobile application for authentication purpose. 

Follow these instructions in order to implement “Token-based authentication with JWT (JSON Web Token) in ASP.NET Core Web API”

Step1

We will be creating the web application in ASP.NET CORE Web API.

Open Visual Studio 2017 》New 》 ASP.NET Core Web Application 》 Web API

Step2

 For add Token-based JWT authentication in our project, we need to add “AddAuthentication” method and provide the “AddJwtBearer” options in ConfigureServices method of Startup.cs

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc()

services.AddIdentity<ApplicationUser, IdentityRole().AddDefaultTokenProviders();

services.AddAuthentication(options => {

options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })

.AddJwtBearer(options =>

{

options.SaveToken = true; options.RequireHttpsMetadata = false;

options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()

{

ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true,

ValidateLifetime=true, ValidAudience= "lionzyinfotech.com", ValidIssuer= "lionzyinfotech.com",

IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySecureKey"))

};

});

}

In the above code, we validate the following points.

  • The server that generates Token (ValidateIssuer)
  • Validation recipient of the token that they authorized to receive (ValidateAudience)
  • Validate the incoming JWT tokens public key(IssuerSigningKey)
  • Validation lifetime of the token that token is not expired(ValidateLifetime)

Step3:

Now In next step that authentication service available to the application, we need to add “UseAuthentication” in configure method of Startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

app.UseAuthentication();

app.UseMvc();

}

 

Step4

In this example, we will add one more controller (AuthController.cs) for authentication and generate JWT token.

Here in this controller, we need to create a method that generates JSON token for authentication.

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using TokenBasedAuth.Model;

using System.Security.Claims;

using System.IdentityModel.Tokens.Jwt;

using Microsoft.IdentityModel.Tokens;

using System.Text;

namespace TokenBasedAuth.Controllers

{

[Route("api/[controller]")]

[ApiController]

public class AuthController : ControllerBase

{

[HttpPost]

[Route("login")]

public IActionResult Index([FromBody] LoginModel model)

{

if (model.Userid == "admin" && model.Password == "admin123")

{

var claims = new[] {

new Claim(JwtRegisteredClaimNames.Sub,model.Userid),

new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())

};

var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecureKey"));

var token = new JwtSecurityToken( issuer: "voidgeeks.com", audience: "voidgeeks.com",

expires: DateTime.UtcNow.AddHours(1), claims: claims,

signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256));

return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration=token.ValidTo

});

};

return Unauthorized();

}

}

}

In the above code Index method expect parameter Userid and Password, for the demo purpose I have provided hardcoded UserId and Password (admin).  Once the user authenticates we need to create JWT using JwtSecurityToken class. We also need to create an object of this class and passing some parameters to constructor like issueraudienceexpiresclaims and signingCredentials. After this, JwtSecurityTokenHandler.WriteToken method used to generate the JWT.

After generating the JWT, I have created a web API that returns a list of values string with HttpGet request. Here I have marked this API Controller with Authorize which will invoke the validation check of the token passed with the HTTP request. If we try to access this controller without a token or with the wrong token then this will return 401(Unauthorized) HTTP status code.

API Controller has the following code snippet.

[Authorize]

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

[HttpGet]

public ActionResult<IEnumerable<string>> Get()

{

return new string[] { "value1", "value2" };

}

}

For test the API use any API tester, here I am using Talend API tester. For generating JWT we need to call /api/auth/login with the POST method. I have passed following credential in JSON request body.

 

This method returned following JSON response in the body.

 

This response contains token and their expiration time for authenticating the user.

Now we will access the list of values string by proving the above token in Authorization HTTP headers.

 

Now we will get the following response.

 

 

Thanks, If you like this article please share with your friends.


Posted By:

Kunal Arora

Chief Technology Officer at Lionzy Infotech Solutions (LIS). He is a Blogger, Web and Mobile Apps Programmer and Digital Marketer by Profession. He is Passionate about New Technologies and trends running in the Corporate World.

0 Comments

Leave a Comment