前后端分离的站点一般都会用jwt或IdentityServer4之类的生成token的方式进行登录鉴权。这里要说的是小项目没有做前后端分离的时站点登录授权的正确方式。

二、传统的授权方式

这里说一下传统授权方式,传统授权方式用session或cookies来完成。

1.在请求某个Action之前去做校验,验证当前操作者是否登录过,登录过就有权限

2.如果没有权限就跳转到登录页中去

3.传统登录授权用的AOP-Filter:ActionFilter。

具体实现为:

1.增加一个类CurrentUser.cs 保存用户登录信息

.NET Core中的鉴权授权正确方式(.NET5)
 /// <summary>
    /// 登录用户的信息
    /// </summary>
    public class CurrentUser
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 用户名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 账号
        /// </summary>
        public string Account { get; set; }
    }
.NET Core中的鉴权授权正确方式(.NET5)

2.建一个Cookice/Session帮助类CookieSessionHelper.cs

.NET Core中的鉴权授权正确方式(.NET5)
 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 GetCurrentUserByCookie(this HttpContext httpContext)
        {
            httpContext.Request.Cookies.TryGetValue("CurrentUser", out string sUser);
            if (sUser == null)
            {
                return null;
            }
            else
            {
                CurrentUser currentUser = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUser>(sUser);
                return currentUser;
            }
        }

        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<CurrentUser>(sUser);
                return currentUser;
            }
        }
    }
.NET Core中的鉴权授权正确方式(.NET5)

相关文章:

  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-03-02
  • 2022-12-23
  • 2021-08-30
  • 2021-08-20
  • 2022-01-07
猜你喜欢
  • 2022-02-20
  • 2022-12-23
  • 2021-09-15
  • 2021-09-27
  • 2021-07-17
  • 2021-08-10
相关资源
相似解决方案