1. 程式人生 > >Asp.NET MVC用System.Web自帶方法寫入FormsAuthentication驗證

Asp.NET MVC用System.Web自帶方法寫入FormsAuthentication驗證

/// <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;
            }
        }

    }
}