开发者

MVC3 Custom AuthorizeAttribute : how to pass in an object from controller

I have an object that contains all login data, that's in my controller (it was programmed before switching to MVC3).

I'm trying to add authorization to the site, so so far I have:

public LoginObject MyLoginObject
{
   get;
   set;
}

[CustomAuthorization()]
public ActionResult Index()
{
 return View();
}

and

public class CustomAuthorization : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
  开发者_高级运维  return true;
    //should be return myLoginObject.IsLoggedIn;
   }
}

Is there anyway to pass MyLoginObject into the AuthorizeAttribute class? If not could I at least pass in a boolean from the object that specifies if the user is authorized or not?

Edit: My solution based on Zonnenberg's advice.

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}; }
}
}

Then I moved the instantiation of loginobject into CustomAuthorization

public override void OnAuthorization(AuthorizationContext filterContext)
{
  // ... Set up LoginObject
    filterContext.RequestContext.HttpContext.User = myLoginObject;

  base.OnAuthorization(filterContext);
}

So now logging in, is done inside the authorization, and I can call User to access the login from the controller.


You can check wheter the user is logged in by using httpContext.User.Identity.IsAuthenticated.

To store more information you could use the httpContext.User object. You can write your own implementation of IPrincipal and IIdentity to store all kinds of login information.

Other option is to store login info in the Session.


How is your LoginObject instantiated?

If it's instantiated via a service or repository (ex. MyLoginObject = loginService.GetLogin() then you can move this call into the CustomAuthorization attribute.

If the logic is within the controller itself then this should be refactored into a service or repository depending on you solution architecture so that you can do the above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜