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

62 lines
2.6 KiB

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
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.Linq;
using System.Security.Claims;
using System.Text;
namespace Infrastructure.Extensions
{
public static class HttpContextExtensions
{
public static void SignIn(this HttpContext httpContext, string userName, IEnumerable<string> roles, bool rememberMe)
{
var claims = new List<Claim> { new Claim("Name", userName) };
claims.AddRange(roles.Select(o => new Claim("Role", o)).ToList());
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme, "Name", "Role"));
httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties { IsPersistent = rememberMe });
}
public static void SignIn(this HttpContext httpContext, string userName, bool rememberMe, IConfiguration cfg)
{
var token = httpContext.GetToken(userName, rememberMe, cfg, DateTime.Now.AddYears(1));
var cookieOptions = new CookieOptions
{
HttpOnly = true
};
if (rememberMe)
{
cookieOptions.Expires = DateTimeOffset.Now.AddYears(1);
}
httpContext.Response.Cookies.Delete("jwt");
httpContext.Response.Cookies.Append("jwt", token, cookieOptions);
}
public static string GetToken(this HttpContext httpContext, string userName, bool rememberMe, 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<Claim> { 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);
}
}
}