C#

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...

J
Joynal Abedin
6
\"\"

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-

  1. Microsoft.AspNetCore.Authentication.JwtBearer
  2. 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 claims = new List
            {
                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).

1.Register:

\"\"

2. Login:

\"\"


J

Written by Joynal Abedin

Passionate about technology, code, and sharing knowledge.

0 Comments

Leave a Comment