I'm reading from several resources (books and SO answers) about authorization in WebApi.
Suppose I want to add Custom Attribute which allows access only for Certain Users:
Case #1
I've seen this approach of overriding OnAuthorization
, which sets response if something is wrong
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if ( /*check if user OK or not*/)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
}
Case #2
But I've also seen this similar example which also overriding OnAuthorization
but with calling to base
:
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
// If not authorized at all, don't bother
if (actionContext.Response == null)
{
//...
}
}
Then, you check if the
HttpActionContext.Response
is set or not. If it’s not set, it means that the request is authorized and the user is ok
Case #3
But I've also seen this approach of overriding IsAuthorized
:
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
if ( /*check if user OK or not*/)
{
return true;// or false
}
}
}
Case #4
And then I saw similar example one but with calling base.IsAuthorized(context) :
protected override bool IsAuthorized(HttpActionContext context)
{
if (something1 && something2 && base.IsAuthorized(context)) //??
return true;
return false;
}
One more thing
And finally Dominick said here :
You shouldn't override OnAuthorization - because you would be missing [AllowAnonymous] handling.
Questions
1) Which methods should I use :
IsAuthorized
orOnAuthorization
? ( or when to use which)2) when should I call
base.IsAuthorized or
base.OnAuthorization` ?3) Is this how they built it ? that if the response is null then everything is ok ? ( case #2)
NB
Please notice , I'm using ( and want to use ) only AuthorizeAttribute
which already inherits from AuthorizationFilterAttribute
Why ?
Becuase I'm at the first stage in : http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
Anyway Im asking via extending Authorize attribute .