views:

79

answers:

4

Hi,

I realise that I can prevent unauthenticated users from accessing views at controller level by applying the [Authorize] attribute and can also filter views down to individual users or roles using this. However, my question is regarding doing the opposite... Is there a way to deny authenticated users from certain views without having to manually add in checks to see if they're authenticated in the opening lines of the controller code? Ideally an [Unauthorized] attribute or an equivalent if such a thing exists?

The reason for this is that I don't want authenticated users to be able to visit the account creation pages of the site I'm working on, as well as other resources. I realise I could check them in the controller explicitly but I'd prefer to decorate the controller methods if at all possible.

Thanks :)

A: 

A simple way to accomplish this? Just leave the action untagged, and start with:

If(Request.IsAuthenticated)
  // redirect somewhere, or return another view...
Palantir
Thanks for your response. I considered doing this but have opted to follow LukLed's suggestion above.
Mr Bog
A: 

You can write your own authorization filter. Inherit from FilterAttribute and implement IAuthorizationFilter. Call it UnauthorizedAttibute and you will be able to use it like [Authorize].

Hear You can read about filters:

http://www.asp.net/LEARN/mvc/tutorial-14-cs.aspx

LukLed
I've done just this :) Many thanks.
Mr Bog
+2  A: 

This is along the lines of what LukLed was referring to:

public class UnAuthorizedAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool excludeCondition = false;

        if (excludeCondition)
            filterContext.Result = new HttpUnauthorizedResult();
        else
            base.OnAuthorization(filterContext);
    }


}

Simply put in the logic for your excludeCondition. You can also to choose to do things like redirect to other views. Just mark your code with [UnAuthorized]

Bomlin
Many thanks. I would have set this as my accepted answer, but it seems rude to LukLed. I do appreciate the code example though :)
Mr Bog
A: 

this could also be accomplished fairly simply if you are already using a roleprovider. then your actions would just need to be filtered by the appropriate role:

[Authorize(Roles = "Admin, Editor")]
Jamie M