Saturday, October 1, 2022
HomeError SolveHow to generate tokens using Dotnet core

How to generate tokens using Dotnet core

This code is for generating a token for an angular application.

But the same code is used in your other application like if you are making API CALL from React or from other technology.

Code in Visual Studio API Project.

Step 1 ) Create a Security class in VS.

public class Security
    {
        public string token { get; set; }
    }

Step 2) Install Microsoft.AspNetCore.Authentication.JwtBearer using Nuget

Step 3) Create API Controller (SecurityController).

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
 [Route("api/[controller]")]
    [ApiController]
    public class SecurityController : ControllerBase
    {
private string GenerateJSONWebToken(string username)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("AdminLogin@AdminLogin@AdminLogin"));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] { 
                new Claim("Issuer","Admin"),
                new Claim("Admin","true"),
                new Claim(JwtRegisteredClaimNames.UniqueName,username)
            };
            var token = new JwtSecurityToken("Admin",
              "Harshida",
              claims,
              expires: DateTime.Now.AddMinutes(120),
              signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

Step 4) In the Security Controller, find the post method and write the below code

 [HttpPost]
        public IActionResult Post([FromBody] User objUser)
        {
            if (objUser.UserName == "Admin")
            {
                var token = GenerateJSONWebToken(objUser.UserName);
                var security = new Security() { token = token};
                return Ok(security);
            }
            else
            {
                return StatusCode(StatusCodes.Status401Unauthorized, "Not Found");
            }
        }

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments