Need help / advice with the ASP.NET MVC custom IAuthorizationFilter class

I am trying to create my own attribute class IAuthorizationFilter

. Basically, every api call has a query string parameter called "key". I was going to then decorate any actions that require this with a simple authorization attribute.

I was hoping my method OnAuthorization(..)

would just fetch the value of the request parameter if provided. If this were the case and it was legal, then the user would be logged in. otherwise it is not.

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

.

Or should I use instead IActionFilter

?

EDIT: I added in some code to show what I am 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.
}

      

+2


source to share


1 answer


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



To deny access based on the value of the key string value of the key, you can set the Result property of the AuthorizationContext to a value other than zero. This can be set to an instance of the HttpUnauthorizedResult class if you like.

+2


source







All Articles