Authentication is something which the most important part in building a web-based application. This authentication will needed consume for communication or as an interface between applications. We usually use to APIs for interfaces between applications. In this article we will guide about ASP.Net Core 2.0 JWT Authentication Example. For more about the API you can read this article What is an API.
To make the APIs that is made more secure in our security requires authentication, namely Json Web Token (JWT).
What is JSON Web Token?
JSON Web Token or JWT is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information transmitting can be verified and trusted because it is digitally signed. JWTs can be signed using a secret key (with the HMAC algorithm) or a public/private key pair using method RSA or ECDSA.
Although JWTs can be encrypted secret to also provide secrery between parties,in this section we will focus on signed tokens key. Signed tokens can make verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When the tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
When should you use JSON Web Tokens?
Here are some condition scenarios where JSON Web Tokens are useful:
- Authorization: This is the most common scenario for implement JWT. Once the user is logged in, each subsequent request will include the JWT, allowing some users to access routes, services, and resources that are permitted with that token. Single Sign On is one of a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
- Information Exchange: JSON Web Tokens or JWT are a good way of securely transmitting information between parties. Because JWTs can be signed – for example, using properties public/private key pairs – you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.
What is the JSON Web Token structure?
In its compact form, JSON Web Tokens consist have three parts separated by dots (.), which are:
- Header
- Payload
- Signature
Therefore, a JWT typically display like the following.
xxxxx.yyyyy.zzzzz
Let’s break down the different parts.
You can see more about JWT in this section Introduction JWT.
Generate ASP.Net Core 2.0 JWT Authentication
In this section, I will tell you how to make a token number starting from making a project in Microsoft Visual Studio until generating a token using Postman. You can also follow this instruction directly using your computer.
- Create new project with Microsoft Visual Studio 2017 or etc to start practice.
- Edit file with name appsettings.json as below (key: yourkey, issuer: hostname:port):
12345678910111213141516171819{"Logging": {"IncludeScopes": false,"Debug": {"LogLevel": {"Default": "Warning"}},"Console": {"LogLevel": {"Default": "Warning"}}},"Jwt": {"Key": "camellabs.com2019!","Issuer": "http://localhost:5008"}} - Setting properties the project look like below:
- The program class is a console app item that is the main entry point to start the application, it configures and launches the web api host and web server using an instance of WebHostBuilder. ASP.NET Core applications require a host in which to execute. Edit program class as below for ASP.Net Core 2.0 JWT Authentication Example:
12345678910111213141516171819202122232425262728using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.Logging;namespace ExampleJWT{public class Program{public static void Main(string[] args){BuildWebHost(args).Run();}public static IWebHost BuildWebHost(string[] args) =>WebHost.CreateDefaultBuilder(args).UseKestrel().UseUrls("http://localhost:5008").UseIISIntegration().UseStartup<Startup>().Build();}} - The startup class configures the request pipeline of the application and how all requests are handled. Edit startup class as below for ASP.Net Core 2.0 JWT Authentication Example:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Options;using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.IdentityModel.Tokens;using System.Text;namespace ExampleJWT{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.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();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseAuthentication();app.UseMvc();}}} - Create TokenModel.cs like Entity to access data between different class of application.
1234567891011121314151617181920using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Threading.Tasks;namespace ExampleJWT.Models{public class AccessToken{[Key]public int id { get; set; }public string name { get; set; }public string email { get; set; }public string username { get; set; }public string password { get; set; }public string token { get; set; }public DateTime? dateexpd { get; set; }}} - Create new class with name TokenController.cs to define and handled all routes / endpoint for the api request or request. This controller will include authentication and standard CRUD operations. The controller actions are secured properties with JWT using the [Authorize] attribute, with the exception of the Authenticate method which allows connection public access by overriding the [Authorize] attribute on the controller with [AllowAnonymous] attribute on the action method. I chose to this approach so any new action methods added to the controller will be secure by default unless explicitly made public.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using Microsoft.AspNetCore.Authorization;using ExampleJWT.Models;using Microsoft.IdentityModel.Tokens;using System.IdentityModel.Tokens.Jwt;using System.Text;namespace ExampleJWT.Controllers{[Route("api/[controller]")]public class TokenController : Controller{private IConfiguration _config;public TokenController(IConfiguration config){_config = config;}[AllowAnonymous][HttpPost]public async Task<IActionResult> CreateToken([FromBody]AccessToken access){IActionResult response = Unauthorized();var user = Authenticate(access);if (user != null){var tokenString = BuildToken(access);response = Ok(new { token = tokenString });var datepd = DateTime.UtcNow.AddHours(7).AddYears(3); //Expired Tokenuser.password = access.password;user.token = tokenString.ToString();user.dateexpd = datepd;}return response;}private string BuildToken(AccessToken access){var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);var token = new JwtSecurityToken(_config["Jwt:Issuer"],_config["Jwt:Issuer"],expires: DateTime.UtcNow.AddHours(7).AddYears(3),signingCredentials: creds);return new JwtSecurityTokenHandler().WriteToken(token);}private AccessToken Authenticate(AccessToken access){AccessToken data = new AccessToken();if (access.username == "camellabs" && access.password == "camellabs"){data = access;}else{data = null;}return data;}}} - Next Step,Running the application with IIS Express In Microsoft visual studio 2017.
- Testing the application if already running with postman like below use method POST :
You can see ASP.Net Core 2.0 JWT Authentication Example Github in Here.
Thank you for reading this article about ASP.Net Core 2.0 JWT Authentication Example, I hope this article is useful for you. Visit My Github about ASP.Net Core in Here