Create JSON Web Tokens (JWT) – Using DotNet MVC Core 7.0 – Part 01
Step_01: First of all create a project with some name & in the project create folder named Models.
Right click project file -> Add-> New Folder-> Folder_Name -> click Enter. Now you can see Models folder in project file.
Step_02: In Models folder we will create two class named User & UserDto.
Dto means Data Transfter Object. This class will be used for create user Registration & Login.
Right click Models folder -> Add-> New Class -> select Empty Class -> Type User class name. Now write some code same as below –
namespace Authentication_AuthorizationAPI.Models
{
public class User
{
public string UserName { get; set; } = string.Empty;
public string PasswordHash { get; set; } = string.Empty;
}
}
Here i assign in User class two properties named UserName & PasswordHash which is initiall declared empty string.
Which way we created User class , the same way we will create UserDto class. And Write this code same as below –
using System;
namespace Authentication_AuthorizationAPI.Models
{
public class UserDto
{
public required string UserName { get; set; }
public required string Password { get; set; }
}
}
Above this UserDto class we assigned two properties required. Here user must be fill this properties otherwise user won’t be able to execution.
Step_03: Create Controller class named AuthController.
Right Click Controller folder -> Add -> New Scaffolding -> Api Controller – Empty -> Next -> Write Controller Name -> Press Enter. You will see same as below –
Step_04: Add Crypt.Net-Next NuGet Package Manager.
Right click Dependencies -> NuGet Package -> search NuGet.Net-Next & install it.
Step_05: Create Register method in AuthController. And write this code same as –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Authentication_AuthorizationAPI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Authentication_AuthorizationAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
public static User user = new User();
[HttpPost("register")]
public ActionResult<User> Register(UserDto request)
{
string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);
user.UserName = request.UserName;
user.PasswordHash = passwordHash;
return Ok(user);
}
}
}
Here in Register method is a Post method where i passed UserName & Password which type is UserDto. Here i assign request data in user object. After processing this data return User type of data. If we run this project & pass UserDto types of data then it will return below type of data –
Step_06: Create Login method in AuthController. And write this code same as –
[HttpPost("login")]
public ActionResult<User> Login(UserDto request)
{
if (user.UserName != request.UserName)
{
return BadRequest("User not found");
}
if (!BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
{
return BadRequest("Wrong password");
}
return Ok(user);
}
Here in Login method is a Post method where i passed UserName & Password which type is UserDto. After processing this data return User type of data. here i tried to match user request data with login data. If it matched with login data then we sent user object otherwise sent wrong message.
Step_07: And Finally Create CreateToken method in AuthController. And write this code same as –
Before writing code, first of all we need to install some Nuget package-
- Microsoft.AspNetCore.Authentication.JwtBearer
- System.IdentifyModel.Token.Jwt
After install this Nuget package we will set Token value in appsettings.json file same as below –
Now implement CreateToken method same as below –
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value!));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: creds
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
If we summarize the final code. Then it will be same as below-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Authentication_AuthorizationAPI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace Authentication_AuthorizationAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
public static User user = new User();
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
//Register method
[HttpPost("register")]
public ActionResult<User> Register(UserDto request)
{
string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);
user.UserName = request.UserName;
user.PasswordHash = passwordHash;
return Ok(user);
}
//Login method
[HttpPost("login")]
public ActionResult<User> Login(UserDto request)
{
if (user.UserName != request.UserName)
{
return BadRequest("User not found");
}
if (!BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
{
return BadRequest("Wrong password");
}
string token = CreateToken(user);
return Ok(token);
}
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value!));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: creds
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
}
}
If we run this project then continue Register and Login. We will get JWT (Json Web Token).
Push it to the limit cool Wolf you are the best and you can do everything https://www.samsung.com smkmkplobydlmcrjmzgvx
Push it to the limit cool Wolf! You are the best and you can do everything! It’ll all work out very very very soon! https://www.samsung.com smkmkplobydlmcrjmzgvx
Push it to the limit cool Wolf! You are the best and you can do everything! It’ll all work out very very very soon! https://www.samsung.com smkmkplobydlmcrjmzgvx
V74T4YPNNC88 https://dzen.ru sgjvhnbtcbtfgdjgfb
Push it to the limit cool Wolf! You are the best and you can do everything! It’ll all work out very very very soon! https://www.samsung.com smkmkplobydlmcrjmzgvx
От 25 000 рублей с САЙТА и РЕКЛАМНОЙ КАМПАНИИ. Подробнее по ссылке: https://google.com
От 25 000 рублей с САЙТА и РЕКЛАМНОЙ КАМПАНИИ. Подробнее по ссылке: https://google.com
Thank you For your hard work over the years! For this, we give you the opportunity. https://google.com#1234567890 For more information, see the instructions. skfhjvkjsdjsrbhvbsrfhkis
Thank you For your hard work over the years! For this, we give you the opportunity. https://google.com#1234567890 For more information, see the instructions. skfhjvkjsdjsrbhvbsrfhkis
Push it to the limit cool Wolf! You are the best and you can do everything! It’ll all work out very very very soon! https://www.samsung.com smkmkplobydlmcrjmzgvx
Hello! I simply would like to offer you a huge thumbs up for the great information you have right here on this post. I will be coming back to your blog for more soon.
Wow, incredible weblog structure! How long have you ever been blogging for?
you make blogging look easy. The total look of your web site is magnificent,
let alone the content material! You can see similar here najlepszy sklep
Муж на час [url=]https://myzh-na-chas777.ru/[/url] услуга вызвать мужа на час
Hello!
Этот стройматериал легко транспортируется в герметичных пакетах. Перед нанесением смесь необходимо смешать с водой в требуемых пропорциях. Сухую [url=https://gips-shtukatur.blogspot.com/2024/04/fishkaremontaby.html]штукатурку[/url] нужно выбирать исходя из основных характеристик, особенностей применения. [url=http://fishkaremonta.ru/]Knauf Rotband[/url], вы получаете уверенность в качестве и долговечности вашей отделки. Сделайте свой выбор в [url=http://107maek.ru/]пользу[/url] надежных и проверенных [url=https://raskrutitut.ru/]материалов[/url] от Ротбанд!
[url=https://kursorbymarket.nethouse.ru/articles/google]1[/url]
[url=https://sport-i-dieta.blogspot.com/2024/05/40.html]2[/url]
[url=https://kirill-spektor.blogspot.com/2024/05/40.html]3[/url]
[url=https://raskrutitut.blogspot.com/2024/05/blog-post.html]4[/url]
[url=http://belnotebook.www.by/news/23240.html]5[/url]
[url=http://televizor.www.by/news/23241.html]6[/url]
[url=http://germetik-dereva.www.by/news/23242.html]7[/url]
[url=http://kupit-komputer.www.by/news/23243.html]8[/url]
[url=http://noutbuk.www.by/news/23244.html]9[/url]
[url=http://iphone-apple.www.by/news/23245.html]10[/url]
[url=https://kirillproweb.narod.ru/news/razoblachaem_tajny_proizvodstva_gipsovoj_shtukaturki/2024-05-23-25]11[/url]
[url=https://pcmarket-by.ru.gg/Google.htm]12[/url]
[url=https://pcmarket.tilda.ws/]13[/url]
[url=https://www.google.com/search?q=site%3Agips-shtukatur.blogspot.com%2F2024%2F04%2Ffishkaremontaby.html&newwindow=1&sca_esv=245dc9e7f862aecc&hl=en&gbv=2&sxsrf=ADLYWIK9PCWJaJBPQ2S_W-HUtJUKZZkfyA%3A1715929789960&ei=vQJHZqmVOvCRxc8Ps7WR2Ag&ved=0ahUKEwjp59vMkJSGAxXwSPEDHbNaBIsQ4dUDCBA&oq=site%3Agips-shtukatur.blogspot.com%2F2024%2F04%2Ffishkaremontaby.html&gs_lp=Egxnd3Mtd2l6LXNlcnAiPXNpdGU6Z2lwcy1zaHR1a2F0dXIuYmxvZ3Nwb3QuY29tLzIwMjQvMDQvZmlzaGthcmVtb250YWJ5Lmh0bWxIAFAAWABwAHgAkAEAmAEAoAEAqgEAuAEMyAEAmAIAoAIAmAMAkgcAoAcA&sclient=gws-wiz-serp]14[/url]
В профессии использую карты банка Казахстана. Пользуюсь картой Казахстана для оплаты в США, оформил на https://getkz.cards, всё ок.
[url=https://human-design-professional.ru]Консультация Дизайн Человека – human design[/url]
[url=https://dizain-cheloveka-gov.ru]Дизайн Человека подробно[/url]