Authentication And Authorization In ASP.NET 5 With JWT And Swagger

Introduction


Authentication is the process of validating user credentials and authorization is the process of checking privileges for a user to access specific modules in an application. In this article, we will see how to protect an ASP.NET 5 Web API application by implementing JWT authentication.

Swagger


Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software tools to design, build, document, and use RESTful web services. Swagger includes automated documentation, code generation, and test-case generation. Swashbuckle is an open-source project for generating Swagger documents for Web APIs.
We will enable authorization of swagger in this application, so that we can execute authentication protected API requests using swagger.

Create ASP.NET 5 Web API using Visual Studio 2019


Before creating .NET 5 applications, you must install .NET 5 SDK in your system. You should upgrade your Visual Studio 2019 also.
 
 
You must choose .NET core version to 5 from the dropdown and also deselect the default Open API support. We can enable swagger manually later.
 
We must install below libraries using NuGet package manager.
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.AspNetCore.Identity
  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Swashbuckle.AspNetCore
We can modify the appsettings.json with below SQL connection string values and authentication details.
 
appsettings.json
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "AllowedHosts""*",  
  10.   "ConnectionStrings": {  
  11.     "ConnStr""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SarathlalDB;Integrated Security=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"  
  12.   },  
  13.   "JWT": {  
  14.     "ValidAudience""http://localhost:4200",  
  15.     "ValidIssuer""http://localhost:59921",  
  16.     "Secret""StrONGKAutHENTICATIONKEy"  
  17.   }  
  18. }  
We have added a database connection string and also added valid audience, valid issuer and secret key for JWT authentication in above settings file.
 
Create an “ApplicationUser” class inside a new folder “Authentication” which will inherit the IdentityUser class. IdentityUser class is a part of Microsoft Identity framework. We will create all the authentication related files inside the “Authentication” folder.
 
ApplicationUser.cs
  1. using Microsoft.AspNetCore.Identity;  
  2.   
  3. namespace JWTAuthenticationWithSwagger.Authentication  
  4. {  
  5.     public class ApplicationUser : IdentityUser  
  6.     {  
  7.     }  
  8. }  
We can create the “ApplicationDbContext” class and add below code.
 
ApplicationDbContext.cs
  1. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
  2. using Microsoft.EntityFrameworkCore;  
  3.   
  4. namespace JWTAuthenticationWithSwagger.Authentication  
  5. {  
  6.     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  
  7.     {  
  8.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)  
  9.         {  
  10.         }  
  11.     }  
  12. }  
Create class “RegisterModel” for new user registration.
 
RegisterModel.cs
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace JWTAuthenticationWithSwagger.Authentication  
  4. {  
  5.     public class RegisterModel  
  6.     {  
  7.         [Required(ErrorMessage = "User Name is required")]  
  8.         public string Username { getset; }  
  9.   
  10.         [EmailAddress]  
  11.         [Required(ErrorMessage = "Email is required")]  
  12.         public string Email { getset; }  
  13.   
  14.         [Required(ErrorMessage = "Password is required")]  
  15.         public string Password { getset; }  
  16.     }  
  17. }  
Create class “LoginModel” for user login.
 
LoginModel.cs
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace JWTAuthenticationWithSwagger.Authentication  
  4. {  
  5.     public class LoginModel  
  6.     {  
  7.         [Required(ErrorMessage = "User Name is required")]  
  8.         public string Username { getset; }  
  9.   
  10.         [Required(ErrorMessage = "Password is required")]  
  11.         public string Password { getset; }  
  12.     }  
  13. }  
We can create a class “Response” for returning the response value after user registration and user login. It will also return error messages, if the request fails.
 
Response.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace JWTAuthenticationWithSwagger.Authentication  
  7. {  
  8.     public class Response  
  9.     {  
  10.         public string Status { getset; }  
  11.         public string Message { getset; }  
  12.     }  
  13. }  
We can create an API controller “AuthenticateController” inside the “Controllers” folder and add below code.
 
AuthenticateController.cs
  1. using JWTAuthenticationWithSwagger.Authentication;  
  2. using Microsoft.AspNetCore.Http;  
  3. using Microsoft.AspNetCore.Identity;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.IdentityModel.Tokens;  
  7. using System;  
  8. using System.Collections.Generic;  
  9. using System.IdentityModel.Tokens.Jwt;  
  10. using System.Security.Claims;  
  11. using System.Text;  
  12. using System.Threading.Tasks;  
  13.   
  14. namespace JWTAuthenticationWithSwagger.Controllers  
  15. {  
  16.     [Route("api/[controller]")]  
  17.     [ApiController]  
  18.     public class AuthenticateController : ControllerBase  
  19.     {  
  20.         private readonly UserManager<ApplicationUser> userManager;  
  21.         private readonly IConfiguration _configuration;  
  22.   
  23.         public AuthenticateController(UserManager<ApplicationUser> userManager, IConfiguration configuration)  
  24.         {  
  25.             this.userManager = userManager;  
  26.             _configuration = configuration;  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         [Route("login")]  
  31.         public async Task<IActionResult> Login([FromBody] LoginModel model)  
  32.         {  
  33.             var user = await userManager.FindByNameAsync(model.Username);  
  34.             if (user != null && await userManager.CheckPasswordAsync(user, model.Password))  
  35.             {  
  36.                 var userRoles = await userManager.GetRolesAsync(user);  
  37.   
  38.                 var authClaims = new List<Claim>  
  39.                 {  
  40.                     new Claim(ClaimTypes.Name, user.UserName),  
  41.                     new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),  
  42.                 };  
  43.   
  44.                 foreach (var userRole in userRoles)  
  45.                 {  
  46.                     authClaims.Add(new Claim(ClaimTypes.Role, userRole));  
  47.                 }  
  48.   
  49.                 var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));  
  50.   
  51.                 var token = new JwtSecurityToken(  
  52.                     issuer: _configuration["JWT:ValidIssuer"],  
  53.                     audience: _configuration["JWT:ValidAudience"],  
  54.                     expires: DateTime.Now.AddHours(3),  
  55.                     claims: authClaims,  
  56.                     signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)  
  57.                     );  
  58.   
  59.                 return Ok(new  
  60.                 {  
  61.                     token = new JwtSecurityTokenHandler().WriteToken(token),  
  62.                     expiration = token.ValidTo  
  63.                 });  
  64.             }  
  65.             return Unauthorized();  
  66.         }  
  67.   
  68.         [HttpPost]  
  69.         [Route("register")]  
  70.         public async Task<IActionResult> Register([FromBody] RegisterModel model)  
  71.         {  
  72.             var userExists = await userManager.FindByNameAsync(model.Username);  
  73.             if (userExists != null)  
  74.                 return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" });  
  75.   
  76.             ApplicationUser user = new ApplicationUser()  
  77.             {  
  78.                 Email = model.Email,  
  79.                 SecurityStamp = Guid.NewGuid().ToString(),  
  80.                 UserName = model.Username  
  81.             };  
  82.             var result = await userManager.CreateAsync(user, model.Password);  
  83.             if (!result.Succeeded)  
  84.                 return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." });  
  85.   
  86.             return Ok(new Response { Status = "Success", Message = "User created successfully!" });  
  87.         }  
  88.   
  89.     }  
  90. }  
We have added two methods “login” and “register” inside the controller class. Register method will be used to create new user information. In login method, we have returned a JWT token after successful login.
 
We can make below changes in “ConfigureServices” and “Configure” methods in “Startup” class.

Startup.cs
  1. using JWTAuthenticationWithSwagger.Authentication;  
  2. using Microsoft.AspNetCore.Authentication.JwtBearer;  
  3. using Microsoft.AspNetCore.Builder;  
  4. using Microsoft.AspNetCore.Hosting;  
  5. using Microsoft.AspNetCore.Identity;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using Microsoft.EntityFrameworkCore;  
  8. using Microsoft.Extensions.Configuration;  
  9. using Microsoft.Extensions.DependencyInjection;  
  10. using Microsoft.Extensions.Hosting;  
  11. using Microsoft.Extensions.Logging;  
  12. using Microsoft.IdentityModel.Tokens;  
  13. using Microsoft.OpenApi.Models;  
  14. using System;  
  15. using System.Collections.Generic;  
  16. using System.Linq;  
  17. using System.Text;  
  18. using System.Threading.Tasks;  
  19.   
  20. namespace JWTAuthenticationWithSwagger  
  21. {  
  22.     public class Startup  
  23.     {  
  24.         public Startup(IConfiguration configuration)  
  25.         {  
  26.             Configuration = configuration;  
  27.         }  
  28.   
  29.         public IConfiguration Configuration { get; }  
  30.   
  31.         // This method gets called by the runtime. Use this method to add services to the container.  
  32.         public void ConfigureServices(IServiceCollection services)  
  33.         {  
  34.   
  35.             services.AddControllers();  
  36.             services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));  
  37.   
  38.             // For Identity  
  39.             services.AddIdentity<ApplicationUser, IdentityRole>()  
  40.                 .AddEntityFrameworkStores<ApplicationDbContext>()  
  41.                 .AddDefaultTokenProviders();  
  42.   
  43.             // Adding Authentication  
  44.             services.AddAuthentication(options =>  
  45.             {  
  46.                 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;  
  47.                 options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;  
  48.                 options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  
  49.             })  
  50.   
  51.             // Adding Jwt Bearer  
  52.             .AddJwtBearer(options =>  
  53.             {  
  54.                 options.SaveToken = true;  
  55.                 options.RequireHttpsMetadata = false;  
  56.                 options.TokenValidationParameters = new TokenValidationParameters()  
  57.                 {  
  58.                     ValidateIssuer = true,  
  59.                     ValidateAudience = true,  
  60.                     ValidAudience = Configuration["JWT:ValidAudience"],  
  61.                     ValidIssuer = Configuration["JWT:ValidIssuer"],  
  62.                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))  
  63.                 };  
  64.             });  
  65.   
  66.             services.AddSwaggerGen(swagger =>  
  67.             {  
  68.                 //This is to generate the Default UI of Swagger Documentation    
  69.                 swagger.SwaggerDoc("v1"new OpenApiInfo  
  70.                 {  
  71.                     Version = "v1",  
  72.                     Title = "ASP.NET 5 Web API",  
  73.                     Description = "Authentication and Authorization in ASP.NET 5 with JWT and Swagger"  
  74.                 });  
  75.                 // To Enable authorization using Swagger (JWT)    
  76.                 swagger.AddSecurityDefinition("Bearer"new OpenApiSecurityScheme()  
  77.                 {  
  78.                     Name = "Authorization",  
  79.                     Type = SecuritySchemeType.ApiKey,  
  80.                     Scheme = "Bearer",  
  81.                     BearerFormat = "JWT",  
  82.                     In = ParameterLocation.Header,  
  83.                     Description = "Enter 'Bearer' [space] and then your valid token in the text input below.\r\n\r\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\"",  
  84.                 });  
  85.                 swagger.AddSecurityRequirement(new OpenApiSecurityRequirement  
  86.                 {  
  87.                     {  
  88.                           new OpenApiSecurityScheme  
  89.                             {  
  90.                                 Reference = new OpenApiReference  
  91.                                 {  
  92.                                     Type = ReferenceType.SecurityScheme,  
  93.                                     Id = "Bearer"  
  94.                                 }  
  95.                             },  
  96.                             new string[] {}  
  97.   
  98.                     }  
  99.                 });  
  100.             });  
  101.         }  
  102.   
  103.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  104.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  105.         {  
  106.             if (env.IsDevelopment())  
  107.             {  
  108.                 app.UseDeveloperExceptionPage();  
  109.             }  
  110.   
  111.             app.UseSwagger();  
  112.             app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json""ASP.NET 5 Web API v1"));  
  113.   
  114.             app.UseHttpsRedirection();  
  115.   
  116.             app.UseRouting();  
  117.   
  118.             app.UseAuthentication();  
  119.             app.UseAuthorization();  
  120.   
  121.             app.UseEndpoints(endpoints =>  
  122.             {  
  123.                 endpoints.MapControllers();  
  124.             });  
  125.         }  
  126.     }  
  127. }  
We can add “Authorize” attribute inside the existing “WeatherForecast” controller (This controller is created automatically).
 
We must create a database and required tables before running the application. As we are using entity framework, we can use below database migration command with package manger console to create a migration script.
 
“add-migration Initial”
 
Use below command to create database and tables.
 
“update-database”
 
We can run the application and try to access get method in weatherforecast controller using swagger.
 
 
You have got a 401 – Unauthorized error. Because, you have not yet passed a valid token to this method in this controller.
 
We can create new user using register method in Authenticate control using swagger.
 
 
After successful registration, we can get a valid token from login method using the above credentials.
 
 
 
After successful login, you have got a valid token.
 
 
 
We can copy the token value and use in our swagger to authenticate our entire application.
 
 
 
 
We can see an Authorize button in the top of the swagger screen. Please click that button.
 
 
 
 
As mentioned in the description, please add the previously copied token value along with “Bearer “and click “Authorize” button to proceed further.
 
Authorization will be applied to entire application now. We can close the button and check the weatherforecast controller again.
 
 
 
We have successfully received data from weatherforecast controller now.

Conclusion


In this post, we have seen how to create JSON web tokens in .NET 5 Web API and use this token to authenticate and authorize our application. We have enabled swagger documentation and also enabled authentication in swagger. So that, we can check our entire Web API application without using Postman or any other third-party tools.