123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- using System;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using System.Text;
- using Microsoft.Extensions.Configuration;
- using Microsoft.IdentityModel.Tokens;
- namespace BubbleSocketCore.Library
- {
- public class JwtTokenHandler
- {
- private readonly IConfiguration Configuration;
- public JwtTokenHandler(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public JwtSecurityToken ParseToken(string token)
- {
- SecurityToken validatedToken;
- new JwtSecurityTokenHandler().ValidateToken(token, GetParameters(), out validatedToken);
- return validatedToken as JwtSecurityToken;
- }
- public TokenValidationParameters GetParameters()
- {
- return new TokenValidationParameters()
- {
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SecretKey"])),
- ValidateIssuer = true,
- ValidIssuer = Configuration["JwtSettings:Issuer"],
- ValidateAudience = true,
- ValidAudience = Configuration["JwtSettings:Audience"],
- ValidateLifetime = true,
- ClockSkew = TimeSpan.FromMinutes(Configuration.GetValue<int>("JwtSettings:ExpirationInHours"))
- };
- }
- public string GetTokenValue(string token, string key)
- {
- var parsedToken = ParseToken(token);
- dynamic value;
- parsedToken.Payload.TryGetValue(key, out value);
- return value.ToString();
- }
- public string GetTokenName(string token)
- {
- return GetTokenValue(token, ClaimTypes.Name);
- }
- }
- }
|