Skip to content

Instantly share code, notes, and snippets.

@gsedubun
Last active November 8, 2018 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsedubun/c76166503d08e9da13a0ee9159d368da to your computer and use it in GitHub Desktop.
Save gsedubun/c76166503d08e9da13a0ee9159d368da to your computer and use it in GitHub Desktop.
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