roadie/Roadie.Api.Services/TokenService.cs

56 lines
2.3 KiB
C#
Raw Normal View History

2018-11-10 23:26:04 +00:00
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
2018-11-02 21:04:49 +00:00
using Roadie.Library.Identity;
using System;
using System.IdentityModel.Tokens.Jwt;
2018-11-10 23:26:04 +00:00
using System.Linq;
2018-11-02 21:04:49 +00:00
using System.Security.Claims;
2018-11-10 23:26:04 +00:00
using System.Threading.Tasks;
2018-11-02 21:04:49 +00:00
namespace Roadie.Api.Services
{
public class TokenService : ITokenService
{
private readonly IConfiguration _configuration;
public TokenService(IConfiguration configuration)
{
this._configuration = configuration;
}
2018-11-10 23:26:04 +00:00
public async Task<string> GenerateToken(ApplicationUser user, UserManager<ApplicationUser> userManager)
2018-11-02 21:04:49 +00:00
{
var utcNow = DateTime.UtcNow;
2018-11-10 23:26:04 +00:00
var roles = await userManager.GetRolesAsync(user);
var userRoles = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToArray();
2018-11-02 21:04:49 +00:00
var tokenHandler = new JwtSecurityTokenHandler();
var claims = new Claim[]
{
2018-12-16 23:37:19 +00:00
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim("roadie_id", user.RoadieId.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, utcNow.ToString())
2018-11-10 23:26:04 +00:00
}.Union(userRoles);
2018-11-02 21:04:49 +00:00
var now = DateTime.UtcNow;
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(this._configuration.GetValue<String>("Tokens:PrivateKey")));
var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
var jwt = new JwtSecurityToken(
signingCredentials: signingCredentials,
claims: claims,
notBefore: utcNow,
expires: utcNow.AddSeconds(this._configuration.GetValue<int>("Tokens:Lifetime")),
audience: this._configuration.GetValue<String>("Tokens:Audience"),
issuer: this._configuration.GetValue<String>("Tokens:Issuer")
);
return new JwtSecurityTokenHandler().WriteToken(jwt);
}
}
}