Skip to content

Instantly share code, notes, and snippets.

Last active November 8, 2018 10:06
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
public class AuthController : Controller
private IConfiguration _config;
public AuthController( IConfiguration config)
this._config = config;
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"],
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