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