Question

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.
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top