mercredi 29 juillet 2015

Web API 2 - Controller - Custom AuthorizeAttribute

I need to add Security to my Web API calls. As I will need custom validation, I decided to create a custom AuthorizeAttribute (I will need to be able to check the current principal).

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CliCWebAuthorize : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK);

        using (var mgr = AuthenticationManager.CreateNew())
        {
            if (!mgr.IsAllowedAccess(actionContext.RequestContext.Principal))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }

        var isAuthorized = actionContext.Response.StatusCode == HttpStatusCode.OK;

        return isAuthorized;
    }        
}

I have a Controller action defined like this:

[HttpGet]
[CliCWebAuthorize]
public IHttpActionResult TestPrdAccess()
{
    return Ok(true);
}

If I access the associated url, the debugger breaks at the custom attribute code (and goes through the code without error), but regardless of true or false, it doesn't go into the Controller method. Nor do I see anything on the browser.

Any help?

Aucun commentaire:

Enregistrer un commentaire