roadie/Roadie.Api.Services/TokenService.cs

60 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;
2019-06-30 22:14:36 +00:00
using Microsoft.IdentityModel.Tokens;
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;
2019-06-30 22:14:36 +00:00
using System.Text;
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)
{
2019-06-30 22:14:36 +00:00
_configuration = configuration;
2018-11-02 21:04:49 +00:00
}
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();
2019-06-30 22:14:36 +00:00
var claims = new[]
2018-11-02 21:04:49 +00:00
{
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;
2019-06-30 22:14:36 +00:00
var securityKey =
new SymmetricSecurityKey(
Encoding.Default.GetBytes(_configuration.GetValue<string>("Tokens:PrivateKey")));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
2018-11-02 21:04:49 +00:00
var jwt = new JwtSecurityToken(
signingCredentials: signingCredentials,
claims: claims,
notBefore: utcNow,
2019-06-30 22:14:36 +00:00
expires: utcNow.AddSeconds(_configuration.GetValue<int>("Tokens:Lifetime")),
audience: _configuration.GetValue<string>("Tokens:Audience"),
issuer: _configuration.GetValue<string>("Tokens:Issuer")
);
2018-11-02 21:04:49 +00:00
return new JwtSecurityTokenHandler().WriteToken(jwt);
}
}
}