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.
iot/projects/Infrastructure/Extensions/HttpContextExtensions.cs

78 lines
2.9 KiB

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Infrastructure.Extensions
{
public static class HttpContextExtensions
{
public static string GetJwtCookieName(this HttpContext httpContext)
{
if (httpContext is null)
{
throw new ArgumentNullException(nameof(httpContext));
}
return httpContext.RequestServices.GetService<IConfiguration>().GetAppSettings("JWT")?["cookie"]??"jwt";
}
public static void JwtSignIn(this HttpContext httpContext, List<Claim> claims, bool rememberMe)
{
if (httpContext is null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var token = httpContext.CreateJwtToken(claims, 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)
{
if (httpContext is null)
{
throw new ArgumentNullException(nameof(httpContext));
}
httpContext.Response.Cookies.Delete(httpContext.GetJwtCookieName());
}
public static string CreateJwtToken(this HttpContext httpContext, List<Claim> claims, DateTime expires)
{
if (httpContext is null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var cfg = httpContext.RequestServices.GetRequiredService<IConfiguration>();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg.GetAppSettings("JWT")["key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: cfg["jwt:issuer"],
audience: cfg["jwt:audience"],
claims: claims,
expires: expires,
signingCredentials: creds);
var tokenText = httpContext.RequestServices.GetRequiredService<JwtSecurityTokenHandler>().WriteToken(token);
return tokenText;
}
public static JwtSecurityToken ReadToken(this HttpContext httpContext, string token)
{
return httpContext.RequestServices.GetRequiredService<JwtSecurityTokenHandler>().ReadJwtToken(token);
}
}
}