Last active
November 8, 2018 10:06
-
-
Save gsedubun/c76166503d08e9da13a0ee9159d368da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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