tags:

views:

115

answers:

2

Hi!

Let's suppose I don't want to use Membership and want to restrict user's access with ActionFilter.

I know I can create a filter/attribute and override the OnActionExecuting method and further I can put this attribute in a ActionResult.

And let's assume that I have a table named 'tbUsers', it has also an int field named 'certificate' and depending on this 'certificate' value, an user can access an ActionResult or not.

But, how can I, in a OnActionExecuting mehod, check this user's 'certificate' value and grant his access or redirect to a 'NotAllowed.aspx' page?

Thanks!!!

+1  A: 

The ActionExecutingContext has the HttpContext which would include the current User object. You can use this to get the User. You can also use it to access the Session if you wanted to store the information in the Session. You could also put it in an encrypted cookie and access those through the Request.Cookies on the context. You'd want to think about the security implications of that, though I don't see it as being more problematic than the auth cookie.

Checking it against the database and maintaining testability on your filter is a little more tricky. What I've done is to provide two constructors for each filter class. One provides a database factory that will create my data context. I use this in testing and supply a mock database factory that produces a mock or fake database. The normal, parameterless constructor calls the previous constructor with a null factory. When this happens the other constructor creates a new instance of the default factory.

private IDatabaseFactory Factory { get; set; }
public MyFilter( IDatabaseFactory factory )
{
     this.Factory = factory ?? new DefaultDatabaseFactory();
}

public MyFilter() : this(null) { }
tvanfosson
+1  A: 

I would not do it this way. I would implement an IAuthorizationFilter. Authorization filters run before all action filters.

For example, suppose you later put an OutputCache attribute on the action method and it happens to run before your authentication filter. That would be bad! If the content is cached, the authentication filter would never run and people would see cached sensitive data.

Haacked