Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AuthorizationPolicy set status code

I have an AuthorizationHandler and I would like to return a custom statuscode ( or text ) right now I am just trying to make it return 429 ( which is for rate limit but that's not relevant )

public class ReCaptchaHandler : AuthorizationHandler<ReCaptchaRequirement>
{
    private readonly ReCaptcha _reCaptcha;
    private readonly IHttpContextAccessor _accessor;

    public ReCaptchaHandler(ReCaptcha reCaptcha, IHttpContextAccessor accessor)
    {
        _reCaptcha = reCaptcha;
        _accessor = accessor;
    }
    protected override  Task HandleRequirementAsync(AuthorizationHandlerContext context,
        ReCaptchaRequirement requirement)
    {

        context.Fail();
        _accessor.HttpContext.Response.StatusCode = 429;
        return Task.CompletedTask;
    }
}

public class ReCaptchaRequirement :  IAuthorizationRequirement
{
}

as you can see, I am trying to set the status = 429 with _accessor.HttpContext.Response.StatusCode = 429;

I have tried using the http context from var filterContext = context.Resource as AuthorizationFilterContext; and then filterContext.HttpContext

I create my policy as follows

services.AddSingleton<IAuthorizationHandler, ReCaptchaHandler>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
    options.AddPolicy("ReCaptcha",
        policy => policy.Requirements.Add(new ReCaptchaRequirement()));
});

The code runs and protects the route marked with [Authorize(Policy = "ReCaptcha")] but the status is always 400 unless I throw an exception.

like image 387
Steve Drake Avatar asked May 23 '17 13:05

Steve Drake


People also ask

What is IAuthorizationRequirement?

IAuthorizationRequirement is a marker service with no methods, and the mechanism for tracking whether authorization is successful. Each IAuthorizationHandler is responsible for checking if requirements are met: C# Copy.

What is policy based authorization?

Authorization Policy Even when you use claim-based or role-based authorization, you are actually using Policy-based Authorization. A Policy defines a collection of requirements, that the user must satisfy in order to access a resource. The user must satisfy all the requirements.

Under Which method should a policy be registered for it to be a part of authorization service?

First, you have to register your policy in the ConfigureServices() method of the Startup class, as part of the authorization service configuration.


1 Answers

If you set the StatusCode as follows it works

context.Fail();
var Response = filterContext.HttpContext.Response;
var message= Encoding.UTF8.GetBytes("ReCaptcha failed");
Response.OnStarting(async () =>
{
    filterContext.HttpContext.Response.StatusCode = 429;
    await Response.Body.WriteAsync(message, 0, message.Length);
});
like image 165
Steve Drake Avatar answered Sep 22 '22 15:09

Steve Drake