.net core中登录认证的几种方式
2021-03-12 04:28
标签:bytes key jin typeof 检查 相关 filter des let .net core中登录认证的几种方式 第一种、session\cookie+方法过滤器认证 1. 讲解:该认证模式主要的逻辑如下,并且分别在session和cookie中存储相应的值,并且在方法过滤器中进行进行拦截验证。 2. 相关代码如下: 登录控制器 方法过滤器 空白过滤器,目的是为了跳过过滤器 在ConfigureServices中添加如下: 在Configure中添加如下: 还有操作cookie封装的方法: 封装操作Session的 第二种、授权鉴权中间件认证 .net core中登录认证的几种方式 标签:bytes key jin typeof 检查 相关 filter des let 原文地址:https://www.cnblogs.com/wangjinya/p/14515226.html登录的逻辑应该是
session中存储用户的主要信息
key:guid类型
value: 用户的信息
cookie中存储服务端的session的数据类型
key:CurrentUser //这是一个固定的值
value: session中的key的名字
//这是一个空过滤过滤器,表示该控制器里的都不进行过滤
[CustomAllowAnonymous]
public class SessionLoginController : Controller
{
[HttpGet]
public IActionResult SessionLogins(int a)
{
if (a == 1)
{
#region Cookie/Session 自己写 一般使用Sessio为主
CurrentUser currentUser = new CurrentUser()
{
Id = 123,
Name = "wangjin",
Account = "Administrator",
Email = "1293604064",
Password = "123456",
LoginTime = DateTime.Now
};
//生成一个guid的值用来存储主键的值
Guid sessionKey = Guid.NewGuid();
//写Session/写Cookies
base.HttpContext.SetCookies("CurrentUser", sessionKey.ToString(), 30);
//写入session
base.HttpContext.Session.SetString(sessionKey.ToString(), Newtonsoft.Json.JsonConvert.SerializeObject(currentUser));
#endregion
return base.Redirect("/Home/Index");
}
return View();
}
}
///
public class CustomAllowAnonymousAttribute:Attribute
{
}
services.AddSession();
services.AddMvc(option =>
{
option.Filters.Add
app.UseSession();
app.UseCookiePolicy();
public static class CookieSessionHelper
{
public static void SetCookies(this HttpContext httpContext, string key, string value, int minutes = 30)
{
httpContext.Response.Cookies.Append(key, value, new CookieOptions
{
Expires = DateTime.Now.AddMinutes(minutes)
});
}
public static void DeleteCookies(this HttpContext httpContext, string key)
{
httpContext.Response.Cookies.Delete(key);
}
public static string GetCookiesValue(this HttpContext httpContext, string key)
{
httpContext.Request.Cookies.TryGetValue(key, out string value);
return value;
}
public static CurrentUser GetCurrentUserBySession(this HttpContext context)
{
string sUser = context.Session.GetString("CurrentUser");
if (sUser == null)
{
return null;
}
else
{
CurrentUser currentUser = Newtonsoft.Json.JsonConvert.DeserializeObject
public class SessionHelper
{
private IHttpContextAccessor _accessor;
private ISession _session;
private IRequestCookieCollection _requestCookie;
private IResponseCookies _responseCookie;
public SessionHelper(HttpContext context)
{
_session = context.Session;
_requestCookie = context.Request.Cookies;
_responseCookie = context.Response.Cookies;
}
///