ASP.NET Core 2.0 JWT Authentication Example

Introduction 

In this section, I will tell you how to make a token number starting from making a project in Microsoft Visual Studio up to generating a token using Postman. You can follow the instructions directly on your computer.
 
Steps 
  1. Create a new project with Microsoft Visual Studio 2017.
 
  1. Edit file with name appsettings.json as below (key: yourkey, issuer: hostname:port),
    1. {  
    2.   "Logging": {  
    3.     "IncludeScopes"false,  
    4.     "Debug": {  
    5.       "LogLevel": {  
    6.         "Default""Warning"  
    7.       }  
    8.     },  
    9.     "Console": {  
    10.       "LogLevel": {  
    11.         "Default""Warning"  
    12.       }  
    13.     }  
    14.   },  
    15.   "Jwt": {  
    16.     "Key""camellabs.com2019!",  
    17.     "Issuer""http://localhost:5008"  
    18.   }  

     
  2. After setting properties the project looks like shown below:
  1. For the next step, we must edit the program class. This class is a console app item that is the main entry point to start the application, The class was configured and will launch the web API application and web server service using an instance of WebHostBuilder apps.Edit program class as below for ASP.Net Core 2.0 JWT Authentication Example,
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.IO;  
    4. using System.Linq;  
    5. using System.Threading.Tasks;  
    6. using Microsoft.AspNetCore;  
    7. using Microsoft.AspNetCore.Hosting;  
    8. using Microsoft.Extensions.Configuration;  
    9. using Microsoft.Extensions.Logging;  
    10.   
    11. namespace ExampleJWT  
    12. {  
    13.     public class Program  
    14.     {  
    15.         public static void Main(string[] args)  
    16.         {  
    17.             BuildWebHost(args).Run();  
    18.         }  
    19.   
    20.         public static IWebHost BuildWebHost(string[] args) =>  
    21.            WebHost.CreateDefaultBuilder(args)  
    22.                .UseKestrel()  
    23.                .UseUrls("http://localhost:5008")  
    24.                .UseIISIntegration()  
    25.                .UseStartup<Startup>()  
    26.                .Build();  
    27.     }  

  2. We will create a startup class. This class is the request pipeline of the application and how all requests are handled. Edit the startup class as in the below example.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Threading.Tasks;  
    5. using Microsoft.AspNetCore.Builder;  
    6. using Microsoft.AspNetCore.Hosting;  
    7. using Microsoft.Extensions.Configuration;  
    8. using Microsoft.Extensions.DependencyInjection;  
    9. using Microsoft.Extensions.Logging;  
    10. using Microsoft.Extensions.Options;  
    11. using Microsoft.AspNetCore.Authentication.JwtBearer;  
    12. using Microsoft.IdentityModel.Tokens;  
    13. using System.Text;  
    14.   
    15. namespace ExampleJWT  
    16. {  
    17.     public class Startup  
    18.     {  
    19.         public Startup(IConfiguration configuration)  
    20.         {  
    21.             Configuration = configuration;  
    22.         }  
    23.   
    24.         public IConfiguration Configuration { get; }  
    25.   
    26.         // This method gets called by the runtime. Use this method to add services to the container.  
    27.         public void ConfigureServices(IServiceCollection services)  
    28.         {  
    29.             services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  
    30.               .AddJwtBearer(options =>  
    31.               {  
    32.                   options.TokenValidationParameters = new TokenValidationParameters  
    33.                   {  
    34.                       ValidateIssuer = true,  
    35.                       ValidateAudience = true,  
    36.                       ValidateLifetime = true,  
    37.                       ValidateIssuerSigningKey = true,  
    38.                       ValidIssuer = Configuration["Jwt:Issuer"],  
    39.                       ValidAudience = Configuration["Jwt:Issuer"],  
    40.                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))  
    41.                   };  
    42.               });  
    43.   
    44.             services.AddMvc();  
    45.         }  
    46.   
    47.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
    48.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
    49.         {  
    50.             if (env.IsDevelopment())  
    51.             {  
    52.                 app.UseDeveloperExceptionPage();  
    53.             }  
    54.   
    55.   
    56.             app.UseAuthentication();  
    57.             app.UseMvc();  
    58.         }  
    59.     }  

  3. Create TokenModel.cs like Entity to access data between different classes of applications.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel.DataAnnotations;  
    4. using System.Linq;  
    5. using System.Threading.Tasks;  
    6.   
    7. namespace ExampleJWT.Models  
    8. {  
    9.     public class AccessToken  
    10.     {  
    11.         [Key]  
    12.         public int id { getset; }  
    13.         public string name { getset; }  
    14.         public string email { getset; }  
    15.         public string username { getset; }  
    16.         public string password { getset; }  
    17.         public string token { getset; }  
    18.         public DateTime? dateexpd { getset; }  
    19.     }  

  4. Create a new class with nameTokenController.cs to define and handled all routes/endpoints 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 this approach so any new action methods added to the controller will be secure by default unless explicitly made public.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Threading.Tasks;  
    5. using Microsoft.AspNetCore.Mvc;  
    6. using Microsoft.Extensions.Configuration;  
    7. using Microsoft.AspNetCore.Authorization;  
    8. using ExampleJWT.Models;  
    9. using Microsoft.IdentityModel.Tokens;  
    10. using System.IdentityModel.Tokens.Jwt;  
    11. using System.Text;  
    12.   
    13. namespace ExampleJWT.Controllers  
    14. {  
    15.     [Route("api/[controller]")]  
    16.     public class TokenController : Controller  
    17.     {  
    18.         private IConfiguration _config;  
    19.   
    20.         public TokenController(IConfiguration config)  
    21.         {  
    22.             _config = config;  
    23.         }  
    24.   
    25.         [AllowAnonymous]  
    26.         [HttpPost]  
    27.         public async Task<IActionResult> CreateToken([FromBody]AccessToken access)  
    28.         {  
    29.             IActionResult response = Unauthorized();  
    30.             var user = Authenticate(access);  
    31.   
    32.             if (user != null)  
    33.             {  
    34.                 var tokenString = BuildToken(access);  
    35.                 response = Ok(new { token = tokenString });  
    36.   
    37.                 var datepd = DateTime.UtcNow.AddHours(7).AddYears(3); //Expired Token  
    38.   
    39.                 user.password = access.password;  
    40.                 user.token = tokenString.ToString();  
    41.                 user.dateexpd = datepd;  
    42.                   
    43.             }  
    44.   
    45.             return response;  
    46.         }  
    47.   
    48.         private string BuildToken(AccessToken access)  
    49.         {  
    50.             var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));  
    51.             var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);  
    52.   
    53.             var token = new JwtSecurityToken(_config["Jwt:Issuer"],  
    54.               _config["Jwt:Issuer"],  
    55.               expires: DateTime.UtcNow.AddHours(7).AddYears(3),  
    56.               signingCredentials: creds);  
    57.   
    58.             return new JwtSecurityTokenHandler().WriteToken(token);  
    59.         }  
    60.   
    61.         private AccessToken Authenticate(AccessToken access)  
    62.         {  
    63.             AccessToken data = new AccessToken();  
    64.             if (access.username == "camellabs" && access.password == "camellabs")  
    65.             {  
    66.                 data = access;  
    67.             }  
    68.             else  
    69.             {  
    70.                 data = null;  
    71.             }  
    72.               
    73.             return data;  
    74.         }  
    75.     }  

  5. Next Step,Running the application with IIS Express In Microsoft visual studio 2017.

  6. Testing the application. If already running with postman like shown below, use the method POST.


You can see the ASP.Net Core 2.0 JWT Authentication Example on Github Here.
 
Thank you for reading this article about ASP.Net Core 2.0 JWT Authentication. I hope this article is useful to you. Visit My Github about ASP.Net Core Here