1

我有一个包含所有登录数据的对象,它在我的控制器中(它是在切换到 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 从控制器访问登录。

4

2 回答 2

2

您可以使用httpContext.User.Identity.IsAuthenticated检查用户是否登录。

要存储更多信息,您可以使用httpContext.User对象。您可以编写自己的IPrincipalIIdentity实现来存储各种登录信息。

其他选项是将登录信息存储在会话中。

于 2011-06-21T22:20:28.353 回答
0

您的 LoginObject 是如何实例化的?

如果它是通过服务或存储库实例化的(例如,MyLoginObject = loginService.GetLogin()那么您可以将此调用移动到 CustomAuthorization 属性中。

如果逻辑在控制器本身内,则应根据您的解决方案架构将其重构为服务或存储库,以便您可以执行上述操作。

于 2011-06-22T15:52:21.880 回答