/// <summary>
/// 登录
/// </summary>
/// <param name="userId"></param>
/// <param name="isKeepLogin">是否保持登录</param>
public static void LogIn(long userId, bool isKeepLogin)
{
//将userId加密
string userIdEncrypt = SecurityHelper.AESEncrypt("userId","配置的加密key");
FormsAuthentication.SetAuthCookie(userIdEncrypt, isKeepLogin);
}
<system.web>
<authentication mode="Forms">
<!--分钟-->
<forms name=".UserInfo" cookieless="UseDeviceProfile" loginUrl="~/login" timeout="120" slidingExpiration="true" protection="All" path="/" enableCrossAppRedirects="false" />
</authentication>
</system.web>
登录请求里面可以获取到FormsAuthentication设置的“加密用户id”
string userid = HttpContext.Current.User.Identity.Name;
forms认证需要在web.config里面配置system.web里面添加,其中.UserInfo这个值就是被存入客户端浏览器里面的cookie名称
然後再登錄過濾器裡面可以驗證是否登錄,參考代碼
filterContext.HttpContext.User.Identity.IsAuthenticated
“IsAuthenticated”這個值可以獲取到用戶是否登錄,如果登錄了,並且cookie寫入了客戶端,則此值為true,否則為false。可以直接用此值檢查是否登錄狀態有效
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Repair.BMS.UI.Handle
{
/// <summary>
/// 登录验证筛选器
/// </summary>
public sealed class LoginFilter : FilterAttribute, IAuthorizationFilter
{
/// <summary>
/// 是否验证登录,true为要验证登录,false不验证,默认验证
/// </summary>
public bool CheckLogin = true;
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!CheckLogin)
{
return;
}
//如果IsAuthenticated一直为false,请检查Web.config配置节点,
//将<authenticationforms>节点加入<system.web>,参考:
//<authentication mode="Forms">
// <forms name=".UserInfo" loginUrl="~/User/Login" defaultUrl="~/" protection="All" timeout="20" path="/" enableCrossAppRedirects="false" />
//</authentication>
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
JsonResult jsonResult = new JsonResult();
jsonResult.Data = new
{
IsLogout = true,
HasError = true,
Message = "登录过期",
};
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result = jsonResult;
}
else
{
//没有验证用户,去登录
string loginURL = "/User/Login";
RedirectResult redirectResult = new RedirectResult(loginURL);
filterContext.Result = redirectResult;
}
return;
}
}
}
}