JWT Authentication & Authorization in .NET Core 3.1

{“token: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImZ1bGxOYW1lIjoiVmFpYmhhdiBCaGFwa2FyIiwicm9sZSI6IkFkbWluIiwianRpIjoiMTJjY2JmMWQtZDRhOS00ODUyLWE5YTgtMTRiY2Y3NzA0MmQ1IiwiZXhwIjoxNTg2NTAxNzkxLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNi8iLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNi8ifQ.XS3LBDSRMhcJmUi2itgBbPPhrdbX2cFgC7tZ7X_einM”,“userDetails”:{“userName: “admin”,“fullName: “Vaibhav Bhapkar”,“password: “1234”,“userRole: “Admin”}
Example:{“alg”: “HMAC”,“typ”: “JWT”}
Example:HMAC(base64UrlEncode(header) + “.” +base64UrlEncode(payload),secret)
  1. Create a new project:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>{options.RequireHttpsMetadata = false;options.SaveToken = true;options.TokenValidationParameters = new TokenValidationParameters{ValidateIssuer = true,ValidateAudience = true,ValidateLifetime = true,ValidateIssuerSigningKey = true,ValidIssuer = Configuration[“Jwt:Issuer”],ValidAudience = Configuration[“Jwt:Audience”],IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[“Jwt:SecretKey”])),ClockSkew = TimeSpan.Zero};});
“Jwt”: {“SecretKey”: “VaibhavBhapkar”,“Issuer”: “https://localhost:44336/",“Audience”: “https://localhost:44336/"},
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
services.AddAuthorization(config =>{config.AddPolicy(Policies.Admin, Policies.AdminPolicy());config.AddPolicy(Policies.User, Policies.UserPolicy());});
using Microsoft.AspNetCore.Authorization;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace JWTAuthenticationExample.Models{public class Policies{public const string Admin = “Admin”;public const string User = “User”;public static AuthorizationPolicy AdminPolicy(){return new AuthorizationPolicyBuilder().RequireAuthenticatedUser().RequireRole(Admin).Build();}public static AuthorizationPolicy UserPolicy(){return new AuthorizationPolicyBuilder().RequireAuthenticatedUser().RequireRole(User).Build();}}}
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace JWTAuthenticationExample.Models{public class User{public string UserName { get; set; }public string FullName { get; set; }public string Password { get; set; }public string UserRole { get; set; }}}
using System;using System.Collections.Generic;using System.IdentityModel.Tokens.Jwt;using System.Linq;using System.Security.Claims;using System.Text;using System.Threading.Tasks;using JWTAuthenticationExample.Models;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.Logging;using Microsoft.IdentityModel.Tokens;namespace JWTAuthenticationExample.Controllers{[ApiController][Route(“[controller]”)]public class LoginController : ControllerBase{private readonly IConfiguration _config;private List<User> appUsers = new List<User>{new User { FullName = “Vaibhav Bhapkar”, UserName = “admin”, Password = “1234”, UserRole = “Admin” },new User { FullName = “Test User”, UserName = “user”, Password = “1234”, UserRole = “User” }};public LoginController(IConfiguration config){_config = config;}[HttpPost][AllowAnonymous]public IActionResult Login([FromBody]User login){IActionResult response = Unauthorized();User user = AuthenticateUser(login);if (user != null){var tokenString = GenerateJWTToken(user);response = Ok(new{token = tokenString,userDetails = user,});}return response;}User AuthenticateUser(User loginCredentials){User user = appUsers.SingleOrDefault(x => x.UserName == loginCredentials.UserName && x.Password == loginCredentials.Password);return user;}string GenerateJWTToken(User userInfo){var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config[“Jwt:SecretKey”]));var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);var claims = new[]{new Claim(JwtRegisteredClaimNames.Sub, userInfo.UserName),new Claim(“fullName”, userInfo.FullName.ToString()),new Claim(“role”,userInfo.UserRole),new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),};var token = new JwtSecurityToken(issuer: _config[“Jwt:Issuer”],audience: _config[“Jwt:Audience”],claims: claims,expires: DateTime.Now.AddMinutes(30),signingCredentials: credentials);return new JwtSecurityTokenHandler().WriteToken(token);}}}
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using JWTAuthenticationExample.Models;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;namespace JWTAuthenticationExample.Controllers{[ApiController][Route(“[controller]”)]public class UserController : ControllerBase{[HttpGet][Route(“GetUserData”)][Authorize(Policy = Policies.User)]public IActionResult GetUserData(){return Ok(“This is a response from user method”);}[HttpGet][Route(“GetAdminData”)][Authorize(Policy = Policies.Admin)]public IActionResult GetAdminData(){return Ok(“This is a response from Admin method”);}}}

--

--

--

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Dependency Injection in Javascript

Making The Easiest JavaScript Game

JavaScript Algorithms: Merge Sort

Four CSS Tools to Keep Your App in Style in 2019

Your first project with React Native

My first experiment with Three.js

Creating a pixelation filter in Javascript

ARRAY in sas

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vaibhav Bhapkar

Vaibhav Bhapkar

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *

More from Medium

GraphQL in Microservice Architecture with a demo (.NET 5 & Python3)

DDD with various programming languages in my way: part1 typescript

Solve SSL issue when host Identity Server 4 behind nginx

Introduction to MassTransit : Messaging with RabbitMQ