Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 aspnetcore_jwt.AuthServer.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace aspnetcore_jwt.AuthServer.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthController : Controller
{
private IConfiguration _config;
public AuthController( IConfiguration config)
{
this._config = config;
}
[HttpPost]
public IActionResult Token(LoginViewModel loginViewModel ){
//return new JwtTokenHandler
var token = GenerateJSONWebToken(loginViewModel);
return Ok(new { Token = token});
}
private string GenerateJSONWebToken(LoginViewModel userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>(){ new Claim(ClaimTypes.Name, userInfo.username),
new Claim(ClaimTypes.NameIdentifier, userInfo.username)
};
var token = new JwtSecurityToken(_config["Jwt:issuer"],
_config["Jwt:issuer"],
claims,
expires: DateTime.Now.AddMinutes(1),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment