Ole Albers
Ole Albers

Reputation: 9285

Is ist ok to throw a HttpException(401) in custom AuthorizeAttribute?

I have a custom AuthorizeAttribute:

public class MyAuthAttribute:AuthorizeAttribute {
 protected override bool AuthorizeCore(HttpContextBase httpContext) {
    return CurrentUser.Roles.Contains(this.Roles);
 }
}

Now that return Currentuser.Roles works perfectly fine. If it returns false, the Browser displays a 401.

But I want to add additional information like the Roles that were asked for. So instead of the return I would throw an exception myself:

throw new httpException(401,string.Format("User should have been in one of the following roles: {0}",this.Roles);

Is it ok to throw a 401-Exception inside AuthorizeAttribute instead of just returning false? Or are there other (better) ways to get that information to the browser?

Upvotes: 0

Views: 354

Answers (1)

Jon Hanna
Jon Hanna

Reputation: 113232

If you are going to send a 401 then just send the normal 401 with a WWW-Authenticate header (if you aren't using a form of authentication that uses WWW-Authenticate then 401 is completely inappropriate). If you want to give extra information then do so in the body of a custom HTML response that goes with that 401 (it will only be shown if the user cancels out of the authentication prompt).

For any other case where you could do something, but are choosing not to allow a particular user do so, use 403.

Upvotes: 1

Related Questions