2013-09-27 24 views
0

我需要驗證經過身份驗證的用戶是否具有對我的站點的活動成員身份。例如,如果用戶的會員資格處於活動狀態,則他們可以自由瀏覽網站的「僅限會員」區域,而如果其會員資格不活動或已過期,則會自動重定向到網站的帳單區域。他們只能查看某些受限制的頁面。在.NET MVC中實現活動成員資格的驗證

我想通過在FormsAuthentication cookie中存儲用戶的成員失效日期來解決這個問題。我正在使用一個自定義的MembershipProvider,並且已經將用戶的ID存儲在cookie中,所以這很容易做到。身份驗證Cookie設置爲24小時後過期。然後我會檢查他們的成員是否處於活動狀態使用自定義AuthorizeAttribute,就像這樣:

public class MembershipAuthorizeAttribute : AuthorizeAttribute 
{ 
    private readonly bool authorizeMembership; 

    public MembershipAuthorizeAttribute() 
    { 
     this.authorizeMembership = true; 
    } 

    public MembershipAuthorizeAttribute(bool authorizeMembership) 
    { 
     this.authorizeMembership = authorizeMembership; 
    } 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     if (this.authorizeMembership) 
     { 
      // Code to validate the membership hasn't expired 
     } 

     return base.AuthorizeCore(httpContext); 
    } 
} 

然後我就可以裝飾我的控制器這樣:

[MembershipAuthorize] 
public class ActiveMembersController : Controller 
{ 
    // Only users with an active membership can access this controller 
} 

[MembershipAuthorize(false)] 
public class BillingController : Controller 
{ 
    // All members can access this controller 
} 

這是一個好辦法,採取或爲有更清晰/更可取的方法來驗證用戶的會員資格是否有效?我寧願不必爲了檢索用戶的成員過期日期或狀態而在每個請求上都擊中數據庫,這就是爲什麼我想將此值存儲在cookie中的原因。另外,將這個值存儲在FormsAuthentication的Cookie中,還是應該將其存儲在不同的cookie中?

回答

0

將這些信息存儲在一個cookie中並不會讓我成爲正確的方法。原因是,在這個答案https://stackoverflow.com/a/706874/2168278中指出的是cookie存儲在客戶機器中。所以他們可能會被篡改。

將此信息存儲在數據庫中似乎更合適。如果你關心性能,你可以隨時緩存你的查詢。

0

我會採取不同的方式。我將有一個後臺進程來檢查即將到期的會員資格並禁用這些帳戶。

如果用戶嘗試登錄,我會檢查該帳戶是否被禁用,然後採取行動。

相關問題