using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Reflection; using System.Security.Claims; using System.Text; namespace Infrastructure.Extensions { public static class HttpContextExtensions { public static string GetJwtCookieName(this HttpContext httpContext) { return $"jwt-{Assembly.GetEntryAssembly().GetName().Name.ToLower()}"; } public static void JwtSignIn(this HttpContext httpContext, string userName, bool rememberMe, IConfiguration cfg) { var token = httpContext.GetToken(userName, cfg, DateTime.Now.AddYears(1)); var cookieOptions = new CookieOptions { HttpOnly = true }; if (rememberMe) { cookieOptions.Expires = DateTimeOffset.Now.AddYears(1); } var cookieName = httpContext.GetJwtCookieName(); httpContext.Response.Cookies.Delete(cookieName); httpContext.Response.Cookies.Append(cookieName, token, cookieOptions); } public static void JwtSignOut(this HttpContext httpContext) { httpContext.Response.Cookies.Delete(httpContext.GetJwtCookieName()); } public static string GetToken(this HttpContext httpContext, string userName, IConfiguration cfg, DateTime expires) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg["jwt:key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new List { new Claim(ClaimTypes.Name, userName) }; var token = new JwtSecurityToken( issuer: cfg["jwt:issuer"], audience: cfg["jwt:audience"], claims: claims, expires: expires, signingCredentials: creds); var tokenText = new JwtSecurityTokenHandler().WriteToken(token); return tokenText; } public static JwtSecurityToken ReadToken(this HttpContext httpContext, string token) { return new JwtSecurityTokenHandler().ReadJwtToken(token); } } }