views:

180

answers:

1

Hi folks,

i'm trying to make my own IAuthorizationFilter attribute class. Basically, each api call has a query string parameter called 'key'. I was going to then decorate any actions that require this, with the simple authorisation attribute.

I was hoping my OnAuthorization(..) method will then just extract the value of the query parameter, if it was provided. If it was, and it's legit, then the user is Authorised. otherwise, they are not.

I'm not sure how to do this in the OnAuthorization(..) method.

Or should I be using an IActionFilter instead?

EDIT: I've added in some code to show what I'm doing...

public void OnAuthorization(AuthorizationContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }

    ApiKey apiKey = null;
    string queryStringKey = filterContext.HttpContext.Request.QueryString["key"];
    if (!string.IsNullOrEmpty(queryStringKey))
    {
        apiKey = GetApiKey(queryStringKey); // Custom code that checks a dictionary.
    }

    // Do we have a key?
    if (apiKey == null)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }

    // TODO: Is this key allowed for this domain?

    // All is good, so don't do anything else.
}
A: 

You should be able to inspect the HttpContext.Request.QueryString property of the AuthorizationContext parameter passed to the OnAuthorization method.

To deny access based on the value of the Key querstring value, you can set the Result property of the AuthorizationContext parameter to a non-null value. This can, if you want, be set to an instance of the HttpUnauthorizedResult class.

David Andres
what do I need to do to say it's not authorised? filterContext.Result = new HttpUnauthorizedResult();otherwise, keep everything as default?
Pure.Krome
@Pure.Krome: see my edit to this post.
David Andres
So if the value of the Result property is non-null, then they are denied. Where is this checked/handled?
Pure.Krome
For a given action that has Authorize filter(s) or has a parent Controller with an OnAuthorization override, the Authorize checks are made first. The MVC engine will then proceed to execute the action if and only if none of the Authorize steps have indicated failure (by checking the AuthoriztionContext.Result field you are setting in your code).
David Andres