How to generate tokens using Dotnet core

How to generate tokens using Dotnet core, 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;
    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",
              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

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

Leave a Comment