我有一个包含所有登录数据的对象,它在我的控制器中(它是在切换到 MVC3 之前编程的)。
我正在尝试向该站点添加授权,到目前为止,我有:
public LoginObject MyLoginObject
{
get;
set;
}
[CustomAuthorization()]
public ActionResult Index()
{
return View();
}
和
public class CustomAuthorization : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return true;
//should be return myLoginObject.IsLoggedIn;
}
}
无论如何将 MyLoginObject 传递给 AuthorizeAttribute 类?如果不能,我至少可以从指定用户是否被授权的对象中传入一个布尔值?
编辑:我的解决方案基于 Zonnenberg 的建议。
public class LoginObject : IPrincipal // Now extends IPrincipal
{
... //old code
private class IdentityImpl : IIdentity
{
public string AuthenticationType
{
get;
set;
}
public bool IsAuthenticated
{
get;
set;
}
public string Name
{
get;
set;
}
}
public IIdentity Identity
{
get { return new IdentityImpl { AuthenticationType = "Custom Authentication", IsAuthenticated = this.IsLoggedIn, Name = this.Id}; }
}
}
然后我将 loginobject 的实例化移动到 CustomAuthorization
public override void OnAuthorization(AuthorizationContext filterContext)
{
// ... Set up LoginObject
filterContext.RequestContext.HttpContext.User = myLoginObject;
base.OnAuthorization(filterContext);
}
所以现在登录是在授权内完成的,我可以调用 User 从控制器访问登录。