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

47 lines
2.4 KiB

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
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, IEnumerable<string> roles, bool rememberMe, IConfiguration cfg)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg["jwt:key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
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"));
var token = new JwtSecurityToken(
issuer: cfg["jwt:issuer"],
audience: cfg["jwt:audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(rememberMe ? 3600 : 3),
signingCredentials: creds);
var tokenText = new JwtSecurityTokenHandler().WriteToken(token);
var newBearerToken = "Bearer " + tokenText;
httpContext.Response.Cookies.Delete("jwt");
httpContext.Response.Cookies.Append("jwt", tokenText);
//httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties { IsPersistent = rememberMe });
}
}
}