You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.7 KiB
46 lines
1.7 KiB
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Linq;
|
|
|
|
namespace Infrastructure.Web
|
|
{
|
|
public class JwtTokenValidator : ISecurityTokenValidator
|
|
{
|
|
private readonly ServiceProvider _serviceProvider;
|
|
|
|
public JwtTokenValidator(ServiceProvider serviceProvider)
|
|
{
|
|
this._serviceProvider = serviceProvider;
|
|
}
|
|
|
|
public bool CanValidateToken => true;
|
|
|
|
public int MaximumTokenSizeInBytes { get; set; }
|
|
|
|
public bool CanReadToken(string securityToken) => true;
|
|
|
|
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
|
|
{
|
|
try
|
|
{
|
|
validatedToken = new JwtSecurityTokenHandler().ReadJwtToken(securityToken);
|
|
var claims = (validatedToken as JwtSecurityToken).Claims.ToList();
|
|
var userName = claims.FirstOrDefault(o => o.Type == ClaimTypes.Name).Value;
|
|
using var scope = this._serviceProvider.CreateScope();
|
|
var roles = scope.ServiceProvider.GetService<IRoleService>().GetRoles(userName).Select(o => new Claim(ClaimTypes.Role, o));
|
|
claims.AddRange(roles);
|
|
return new ClaimsPrincipal(new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
validatedToken = null;
|
|
Console.WriteLine(ex.ToString());
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
} |