前后端分离的站点一般都会用jwt或IdentityServer4之类的生成token的方式进行登录鉴权。这里要说的是小项目没有做前后端分离的时站点登录授权的正确方式。
二、传统的授权方式
这里说一下传统授权方式,传统授权方式用session或cookies来完成。
1.在请求某个Action之前去做校验,验证当前操作者是否登录过,登录过就有权限
2.如果没有权限就跳转到登录页中去
3.传统登录授权用的AOP-Filter:ActionFilter。
具体实现为:
1.增加一个类CurrentUser.cs 保存用户登录信息
/// <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; }
}
2.建一个Cookice/Session帮助类CookieSessionHelper.cs
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;
}
}
}