Simple JWT Token Generation
This is Controller Section of JWT Token Generation.
- 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 Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.IdentityModel.Tokens;
- using Models;
- using Repository.Interfaces;
- using CentralSageFlickApi.Helper;
- namespace CentralSageFlickApi.Controllers {
- public class AccountController: ControllerBase {
- private readonly IAccountService _accountService;
- private IConfiguration _config;
- public AccountController(IConfiguration config, IAccountService accountService) {
- _config = config;
- _accountService = accountService;
- }#
- region Token Generation
- [AllowAnonymous]
- [HttpPost]
- [Route("~/api/Token/TokenGenerate")]
- public IActionResult Login([FromBody] LoginModel login) {
- IActionResult response = Unauthorized();
- try {
- if (ModelState.IsValid) {
- var user = AuthenticateUser(login.Username, login.AppCode);
- if (user != null) {
- var passwordString = PasswordGeneration.DecryptString(user.PasswordSalt, user.Password);
- if (login.Password.Equals(passwordString)) {
- var tokenString = GenerateJwtToken(user);
- response = Ok(new {
- token = tokenString
- });
- } else {
- response = BadRequest(new {
- message = "Invalid Password!"
- });
- }
- } else {
- response = BadRequest(new {
- message = "Invalid User!"
- });
- }
- } else {
- response = BadRequest(new {
- message = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors)
- .Select(v => v.ErrorMessage + " " + v.Exception))
- });
- }
- } catch (Exception ex) {
- response = BadRequest(new {
- message = ex.Message.ToString()
- });
- }
- return response;
- }
- private string GenerateJwtToken(UserRegisterModel userInfo) {
- var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
- var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
- var claims = new [] {
- new Claim(ClaimTypes.Name, userInfo.Username),
- new Claim(ClaimTypes.Email, userInfo.Email),
- new Claim(ClaimTypes.NameIdentifier, userInfo.AppCode),
- new Claim(ClaimTypes.DateOfBirth, userInfo.AddedDate.ToString("yyyy-MM-dd")),
- 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(Convert.ToInt32(_config["Jwt:Expire"])),
- signingCredentials: credentials);
- return new JwtSecurityTokenHandler().WriteToken(token);
- }
- private UserRegisterModel AuthenticateUser(string userName, string appCode) {
- UserRegisterModel user = _accountService.CheckUser(userName, appCode);
- return user;
- }#
- endregion
- }
- }

Join the conversation! Your thoughts help the community grow.