Introduction

This article is meant to make the process of authentication and authorization easier using JSON Web Tokens and also to check the entire process with Swagger UI rather than PostMan.

What is ASP.Net Core?

ASP.NET Core is an open-source and cloud-optimized web framework for developing modern web applications that can be developed and run on Windows, Linux, and Mac. It includes the MVC framework, which now combines the features of MVC and Web API into a single web programming framework.
  • ASP.NET Core apps can run on .NET Core or on the full .NET Framework.
  • It was built to provide an optimized development framework for apps that are deployed to the cloud or run on-premises.
  • It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions.
  • You can develop and run your ASP.NET Core apps cross-platform on Windows, Mac, and Linux

What is a JSON Web Token?

A JSON Web Token (or JWT) is simply a JSON payload containing a particular claim. The key property of JWTs is that in order to confirm if they are valid we only need to look at the token itself. ... A JWT is made of 3 parts: the Header, the Payload, and the Signature.
Url: https://jwt.io/

What is Swagger and how it is useful in ASP.NET Core Web API?

Swagger
Swagger is a machine-readable representation of a RESTful API that enables support for interactive documentation, client SDK generation, and discoverability.
Swashbuckle is an open-source project for generating Swagger documents for Web APIs that are built with ASP.NET Core MVC.
Create a New Project and select ASP.NET Core Web Application:
Authentication And Authorization In .NET Core Web API Using JWT Token And Swagger UI
After clicking to the next button:
Authentication And Authorization In .NET Core Web API Using JWT Token And Swagger UI
Click on the Create Button to create a Sample API Project.

Create an Authenticate Controller

Create this method under the Authenticate Controller:
  1. private string GenerateJSONWebToken(LoginModel userInfo)
  2. {
  3. var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
  4. var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
  5. var token = new JwtSecurityToken(_config["Jwt:Issuer"],
  6. _config["Jwt:Issuer"],
  7. null,
  8. expires: DateTime.Now.AddMinutes(120),
  9. signingCredentials: credentials);
  10. return new JwtSecurityTokenHandler().WriteToken(token);
  11. }
Create another method for Login Validation to authenticate the user via the Hardcoded method:
  1. private async Task<LoginModel> AuthenticateUser(LoginModel login)
  2. {
  3. LoginModel user = null;
  4. //Validate the User Credentials
  5. //Demo Purpose, I have Passed HardCoded User Information
  6. if (login.UserName == "Jay")
  7. {
  8. user = new LoginModel { UserName = "Jay", Password = "123456" };
  9. }
  10. return user;
  11. }
Create the Login Method to pass the parameters as JSON Format to Validate the User and to generate the Token (JWT).
  1. [AllowAnonymous]
  2. [HttpPost(nameof(Login))]
  3. public async Task<IActionResult> Login([FromBody] LoginModel data)
  4. {
  5. IActionResult response = Unauthorized();
  6. var user = await AuthenticateUser(data);
  7. if (data != null)
  8. {
  9. var tokenString = GenerateJSONWebToken(user);
  10. response = Ok(new { Token = tokenString , Message = "Success" });
  11. }
  12. return response;
  13. }
Authentication And Authorization In .NET Core Web API Using JWT Token And Swagger UI
To use the JWT Token and Swagger, we need to install the above two into our project
Add this Class in Authenticate Controller, as these are the required parameters to validate the User
  1. public class LoginModel
  2. {
  3. [Required]
  4. public string UserName { get; set; }
  5. [Required]
  6. public string Password { get; set; }
  7. }
Authenticate Controller
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IdentityModel.Tokens.Jwt;
  5. using System.Linq;
  6. using System.Runtime.InteropServices.WindowsRuntime;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using Microsoft.AspNetCore.Authentication;
  10. using Microsoft.AspNetCore.Authorization;
  11. using Microsoft.AspNetCore.Mvc;
  12. using Microsoft.Extensions.Configuration;
  13. using Microsoft.IdentityModel.Tokens;
  14. namespace AuthenticationandAuthorization.Controllers
  15. {
  16. public class AuthenticateController : BaseController
  17. {
  18. #region Property
  19. /// <summary>
  20. /// Property Declaration
  21. /// </summary>
  22. /// <param name="data"></param>
  23. /// <returns></returns>
  24. private IConfiguration _config;
  25. #endregion
  26. #region Contructor Injector
  27. /// <summary>
  28. /// Constructor Injection to access all methods or simply DI(Dependency Injection)
  29. /// </summary>
  30. public AuthenticateController(IConfiguration config)
  31. {
  32. _config = config;
  33. }
  34. #endregion
  35. #region GenerateJWT
  36. /// <summary>
  37. /// Generate Json Web Token Method
  38. /// </summary>
  39. /// <param name="userInfo"></param>
  40. /// <returns></returns>
  41. private string GenerateJSONWebToken(LoginModel userInfo)
  42. {
  43. var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
  44. var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
  45. var token = new JwtSecurityToken(_config["Jwt:Issuer"],
  46. _config["Jwt:Issuer"],
  47. null,
  48. expires: DateTime.Now.AddMinutes(120),
  49. signingCredentials: credentials);
  50. return new JwtSecurityTokenHandler().WriteToken(token);
  51. }
  52. #endregion
  53. #region AuthenticateUser
  54. /// <summary>
  55. /// Hardcoded the User authentication
  56. /// </summary>
  57. /// <param name="login"></param>
  58. /// <returns></returns>
  59. private async Task<LoginModel> AuthenticateUser(LoginModel login)
  60. {
  61. LoginModel user = null;
  62. //Validate the User Credentials
  63. //Demo Purpose, I have Passed HardCoded User Information
  64. if (login.UserName == "Jay")
  65. {
  66. user = new LoginModel { UserName = "Jay", Password = "123456" };
  67. }
  68. return user;
  69. }
  70. #endregion
  71. #region Login Validation
  72. /// <summary>
  73. /// Login Authenticaton using JWT Token Authentication
  74. /// </summary>
  75. /// <param name="data"></param>
  76. /// <returns></returns>
  77. [AllowAnonymous]
  78. [HttpPost(nameof(Login))]
  79. public async Task<IActionResult> Login([FromBody] LoginModel data)
  80. {
  81. IActionResult response = Unauthorized();
  82. var user = await AuthenticateUser(data);
  83. if (data != null)
  84. {
  85. var tokenString = GenerateJSONWebToken(user);
  86. response = Ok(new { Token = tokenString , Message = "Success" });
  87. }
  88. return response;
  89. }
  90. #endregion
  91. #region Get
  92. /// <summary>
  93. /// Authorize the Method
  94. /// </summary>
  95. /// <returns></returns>
  96. [HttpGet(nameof(Get))]
  97. public async Task<IEnumerable<string>> Get()
  98. {
  99. var accessToken = await HttpContext.GetTokenAsync("access_token");
  100. return new string[] { accessToken };
  101. }
  102. #endregion
  103. }
  104. #region JsonProperties
  105. /// <summary>
  106. /// Json Properties
  107. /// </summary>
  108. public class LoginModel
  109. {
  110. [Required]
  111. public string UserName { get; set; }
  112. [Required]
  113. public string Password { get; set; }
  114. }
  115. #endregion
  116. }
Base Controller
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Authorization;
  6. using Microsoft.AspNetCore.Mvc;
  7. // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
  8. namespace AuthenticationandAuthorization.Controllers
  9. {
  10. [Produces("application/json")]
  11. [Route("api/[controller]")]
  12. [ApiController]
  13. [Authorize(AuthenticationSchemes = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme)]
  14. public class BaseController : ControllerBase
  15. {
  16. }
  17. }
Add this Property and Constructor to invoke the appsettings.json Secret JWT Key and its Issuer:
  1. private IConfiguration _config;
  2. public AuthenticateController(IConfiguration config)
  3. {
  4. _config = config;
  5. }
Add this code appsettings.json. I have it added as basic key. You can also add it as per your wishes, and under Issuer, add your project URL.
  1. "Jwt": {
  2. "Key": "Thisismysecretkey",
  3. "Issuer": "https://localhost:44371"
  4. },
Add this code to the startup.cs file under the Configure Services method to enable the Swagger and also to generate the JWT Bearer Token.
This method gets called by the runtime. Use this method to add services to the container.
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. app.UseHttpsRedirection();
  8. app.UseRouting();
  9. app.UseAuthorization();
  10. app.UseEndpoints(endpoints =>
  11. {
  12. endpoints.MapControllers();
  13. });
  14. app.UseAuthentication();
  15. // Swagger Configuration in API
  16. app.UseSwagger();
  17. app.UseSwaggerUI(c =>
  18. {
  19. c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
  20. });
  21. }
This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddControllers();
  4. // JWT Token Generation from Server Side.
  5. services.AddMvc();
  6. // Enable Swagger
  7. services.AddSwaggerGen(swagger =>
  8. {
  9. //This is to generate the Default UI of Swagger Documentation
  10. swagger.SwaggerDoc("v1", new OpenApiInfo
  11. {
  12. Version= "v1",
  13. Title = "JWT Token Authentication API",
  14. Description="ASP.NET Core 3.1 Web API" });
  15. // To Enable authorization using Swagger (JWT)
  16. swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
  17. {
  18. Name = "Authorization",
  19. Type = SecuritySchemeType.ApiKey,
  20. Scheme = "Bearer",
  21. BearerFormat = "JWT",
  22. In = ParameterLocation.Header,
  23. Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
  24. });
  25. swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
  26. {
  27. {
  28. new OpenApiSecurityScheme
  29. {
  30. Reference = new OpenApiReference
  31. {
  32. Type = ReferenceType.SecurityScheme,
  33. Id = "Bearer"
  34. }
  35. },
  36. new string[] {}
  37. }
  38. });
  39. });
  40. services.AddAuthentication(option =>
  41. {
  42. option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  43. option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  44. }).AddJwtBearer(options =>
  45. {
  46. options.TokenValidationParameters = new TokenValidationParameters
  47. {
  48. ValidateIssuer = true,
  49. ValidateAudience = true,
  50. ValidateLifetime = false,
  51. ValidateIssuerSigningKey = true,
  52. ValidIssuer = Configuration["Jwt:Issuer"],
  53. ValidAudience = Configuration["Jwt:Issuer"],
  54. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) //Configuration["JwtToken:SecretKey"]
  55. };
  56. });
  57. }
When you run the application, you will get the swagger UI as shown below:
Authentication And Authorization In .NET Core Web API Using JWT Token And Swagger UI
Pass the parameters to generate the token:
  1. {
  2. "Username": "Jay",
  3. "password": "123456"
  4. }
Then click on Execute Button -> Your token will be generated!
Authentication And Authorization In .NET Core Web API Using JWT Token And Swagger UI
Click on the Authorize button and add this token under the Value box.
Add the token in the following manner as shown in the example below i.e Bearer token.
Click on the Authorize Button
Authentication And Authorization In .NET Core Web API Using JWT Token And Swagger UI
Now every method in this document has been authorized!
Git-Hub
If you found this article helps you, Please give it alike
........keep learning !!!!