2016-08-12 105 views
1

我想進行自定義身份驗證,因爲我們有很多控制器,創建適用於所有控制器及其操作(除登錄頁面外)的全局篩選器是有意義的。自定義ASP.NET MVC表單身份驗證

在Global.asax.cs中我加了一個全球過濾器:

public class Global : HttpApplication 
{ 
    void Application_Start(object sender, EventArgs e) // Code that runs on application startup 
    { 
    ... // only showing important part 
    GlobalFilters.Filters.Add(new Filters.AuthenticationUserActionFilter()); 
    ... 
} 

文件AuthenticationUserActionFilter.cs

public class AuthorizeUserActionFilter : System.Web.Mvc.Filters.IAuthenticationFilter 
{ 
    public void OnAuthentication(AuthenticationContext filterContext) 
    { 
    bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousActionFilter), inherit: true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousActionFilter), inherit: true); 

    if (skipAuthorization) // anonymous filter attribute in front of controller or controller method 
     return; 

    // does this always read value from ASPXAUTH cookie ? 
    bool userAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated; 

    if (!userAuthenticated) 
    { 
    filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Login" } }); 
    return; 
    } 

    if(HttpContext.Current.User as Contracts.IUser == null) 
    { 
    // check if IUser is stored in session otherwise retrieve from db 
    // System.Web.HttpContext.Current.User is reseted on every request. 
    // Is it ok to set it from Session on every request? Is there any other better approach? 
    if (HttpContext.Current.Session["User"] != null && HttpContext.Current.Session["User"] as Contracts.IUser != null) 
    { 
     HttpContext.Current.User = HttpContext.Current.Session["User"] as Contracts.IUser; 
    } 
    else 
    { 
     var service = new LoginService(); 
     Contracts.ISer user = service.GetUser(filterContext.HttpContext.User.Identity.Name); 

     HttpContext.Current.Session["User"] = user; 
     HttpContext.Current.User = user; 
    } 
    } 
} 

public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) {} 

}

我登錄的代碼是這樣的(在AccountController.cs) :

[Filters.AllowAnonymousActionFilter] 
[HttpPost] 
public JsonResult Login(string username, string password, bool rememberMe = false) 
{ 
    LoginService service = new LoginService(); 
    Contracts.IUser user = service .Login(username, password); 

    System.Web.HttpContext.Current.Session["User"] = value; 
    System.Web.HttpContext.Current.User = value; 

    // set cookie i.e. ASPX_AUTH, if remember me, make cookie persistent, even if user closed browser 
    if (System.Web.Security.FormsAuthentication.IsEnabled) 
     System.Web.Security.FormsAuthentication.SetAuthCookie(username, rememberMe); 

    return new SuccessResponseMessage().AsJsonNetResult(); 
} 

Contracts.IUser接口:

public interface IUser : IPrincipal 
    { 
    Contracts.IUserInfo UserInfo { get; } 
    Contracts.ICultureInfo UserCulture { get; } 
    } 

我的問題是這樣的:

System.Web.HttpContext.Current.User是reseted在每次請求。對每個請求設置HttpContext.Current.User以及Session值是否可以?還有其他更好的方法嗎?什麼是最佳做法?此外微軟似乎有多種方式來處理這個問題(搜索了很多關於此的文章,也在stackoverflow Custom Authorization in Asp.net WebApi - what a mess?)。儘管他們在asp.net核心中開發了一個新的授權,但對此有很多困惑。

回答

3

一種可能的方法是將用戶作爲ASPXAUTH cookie的UserData部分的一部分進行序列化。這樣你就不需要從每個請求的數據庫中獲取它,並且你不需要使用會話(因爲如果你在Web場中使用會話,你將不得不在數據庫中像這樣持續這個會話,所以你會往返到數據庫反正):

[Filters.AllowAnonymousActionFilter] 
[HttpPost] 
public JsonResult Login(string username, string password, bool rememberMe = false) 
{ 
    LoginService service = new LoginService(); 
    Contracts.IUser user = service.Login(username, password); 

    string userData = Serialize(user); // Up to you to write this Serialize method 
    var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddHours(24), rememberMe, userData); 
    string encryptedTicket = FormsAuthentication.Encrypt(ticket); 
    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)); 

    return new SuccessResponseMessage().AsJsonNetResult(); 
} 

然後在您的自定義授權過濾器,你可以解密票和驗證用戶:

public void OnAuthentication(AuthenticationContext filterContext) 
{ 
    ... your stuff about the AllowAnonymousActionFilter comes here 

    var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 
    if (authCookie == null) 
    { 
     // Unauthorized 
     filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Login" } }); 
     return; 
    } 

    // Get the forms authentication ticket. 
    var authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
    Contracts.ISer user = Deserialize(authTicket.UserData); // Up to you to write this Deserialize method -> it should be the reverse of what you did in your Login action 

    filterContext.HttpContext.User = user; 
} 
+0

因此,這意味着,整個Cookie是保存在客戶端(客戶端不會只發送'會話ID'哪個服務器然後匹配,但客戶端發送所有信息)?我在某處讀到了cookie客戶端大小有4k的限制,但這當然是很多。您通常只需要用戶名,身份證,文化,IP等信息... – broadband