[英]Custom IPrincipal with Forms Authentication in ASP.NET MVC
這應該很簡單,但在我所有的谷歌搜索之后我根本想不出來。 這就是我想要的。 我有一個我想要授權的自定義用戶表(目前沒有角色)。 為此,我必須實現我已經完成的自定義成員資格提供程序。 我的問題是,如何設置自定義IPrincipal到HttpContext.Current.User? 應該在哪里發生? 假設我有以下設置:
public class CustomMembershipProvider : MembershipProvider
{
private IUserRepository _repository;
public CustomMembershipProvider(IUserRepository repository)
{
_repository = repository;
}
public override bool ValidateUser(string username, string password)
{
//check user repository
}
//additional methods omitted for brevity
}
然后我有一個自定義用戶類,實現IPrincipal
和IIdentity
public class CustomUser : IPrincipal
{
public CustomUser(string name, int userId, string additionalInfo)
{
Identity = new CustomIdentity(name, userId, additionalInfo);
}
public IIdentity Identity { get; private set; }
public bool IsInRole(string role)
{
return true;
}
}
public class CustomIdentity : IIdentity
{
public CustomIdentity(string name, int userId, string additionalInfo)
{
Name = name;
UserId = userId;
AdditionalInfo = additionalInfo;
}
public string Name { get; private set; }
public string AuthenticationType
{
get { return "CustomAuth"; }
}
public bool IsAuthenticated
{
get { return !String.IsNullOrEmpty(Name); }
}
public int UserId { get; private set; }
public string AdditionalInfo { get; private set; }
}
所以我的問題是,將Context.User設置為此自定義用戶的實例的正確位置在哪里? 我需要自定義授權屬性嗎? 如果是這樣,那會是什么樣子?
我建議為所有控制器使用自定義控制器基類
然后,在OnAuthorization
,調用
protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
// Actual Authentication
HttpContext.User = user;
Thread.CurrentPrincipal = user;
base.OnAuthorization(filterContext);
}
我不完全確定如何調用成員資格提供程序,因為我正在進行manuallt,但我認為您可以靜態訪問Membership.Provider
來執行實際的對象構造。
我需要自定義授權屬性嗎?
請注意,身份驗證和授權的區別在於:身份驗證可在系統中建立用戶身份。 授權允許或拒絕特定請求。 因此, AuthorizeAttribute
還具有Roles
參數,以允許僅由特定用戶調用操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.