.net core中登录认证的几种方式

2021-03-12 04:28

阅读:435

标签:bytes   key   jin   typeof   检查   相关   filter   des   let   

.net core中登录认证的几种方式

第一种、session\cookie+方法过滤器认证

1. 讲解:该认证模式主要的逻辑如下,并且分别在session和cookie中存储相应的值,并且在方法过滤器中进行进行拦截验证。

登录的逻辑应该是
session中存储用户的主要信息
    key:guid类型
    value: 用户的信息
cookie中存储服务端的session的数据类型
    key:CurrentUser  //这是一个固定的值
    value: session中的key的名字

2. 相关代码如下:

登录控制器

  //这是一个空过滤过滤器,表示该控制器里的都不进行过滤
    [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 CustomActionFilterAttribute : Attribute, IActionFilter
    {
        /// 
        /// 方法执行前
        /// 
        /// 
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //表示如果带有该属性,就不进行下面的步骤,直接返回
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item.GetType() == typeof(CustomAllowAnonymousAttribute))) //如果标记的有特殊的记号,就避开检查;
            {
                return;
            }
            Byte[] bytes;
            context.HttpContext.Session.TryGetValue("CurrentUser", out bytes);
            string cookieKey = CookieSessionHelper.GetCookiesValue(context.HttpContext, "CurrentUser");
            string str = cookieKey != null ? new SessionHelper(context.HttpContext).GetSession(cookieKey) : null;
            if (string.IsNullOrEmpty(str))
            {
                var result = new ViewResult { ViewName = "~/Views/SessionLogin/SessionLogins.cshtml" };
                //result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                //result.ViewData.Add("Exception", context.Exception);
                context.Result = result; //断路器---只要对Result赋值--就不继续往后了;

            }
            Console.WriteLine("这是方法执行前");
        }
        /// 
        /// 方法执行后
        /// 
        /// 
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item.GetType() == typeof(CustomAllowAnonymousAttribute))) //如果标记的有特殊的记号,就避开检查;
            {
                return;
            }
            Console.WriteLine("这是方法执行后");
        }
    }

空白过滤器,目的是为了跳过过滤器

public class CustomAllowAnonymousAttribute:Attribute
    {
    }

在ConfigureServices中添加如下:

services.AddSession();
            services.AddMvc(option =>
            {
                option.Filters.Add(); //全局注册:
                option.Filters.Add(); //全局注册异常过滤器:
            });

在Configure中添加如下:

        app.UseSession();
            app.UseCookiePolicy();

还有操作cookie封装的方法:

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(sUser);
                return currentUser;
            }
        }
    }

封装操作Session的

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;
        }
        /// 
        /// 设置session值
        /// 
        /// 
        /// 
        /// 
        public void SetSession(string key, string value)
        {
            var bytes = System.Text.Encoding.UTF8.GetBytes(value);
            _session.Set(key, bytes);
        }
        /// 
        /// 获取Session值
        /// 
        /// 
        /// 
        public string GetSession(string key)
        {
            Byte[] bytes;
            _session.TryGetValue(key, out bytes);
            var value = System.Text.Encoding.UTF8.GetString(bytes);

            if (string.IsNullOrEmpty(value))
            {
                value = string.Empty;
            }
            return value;
        }
        ///// 
        ///// 设置本地cookie
        ///// 
        ///// 
        ///// 
        ///// 过期时间
        //public void SetCookies(string key,string value,int day = 1)
        //{
        //    _responseCookie.Append(key, value, new CookieOptions
        //    {
        //        Expires = DateTime.Now.AddDays(day)
        //    }) ;
        //}
        //public void  DeleteCookies(string key)
        //{
        //    _responseCookie.Delete(key);
        //}
        //public string GetCookiesValue(string key)
        //{
        //    _requestCookie.TryGetValue(key, out string value);
        //    if (string.IsNullOrEmpty(value))
        //    {
        //        value = string.Empty;
        //    }
        //    return value;
        //}
    }

 

第二种、授权鉴权中间件认证

 

.net core中登录认证的几种方式

标签:bytes   key   jin   typeof   检查   相关   filter   des   let   

原文地址:https://www.cnblogs.com/wangjinya/p/14515226.html

上一篇:HTML-文本标签

下一篇:php之yum安装


评论


亲,登录后才可以留言!