Vinod Kumar Kuruba
Vinod Kumar Kuruba

Reputation: 21

Return 401 for Custom Authrization

how to return 401?

protected override async Task HandleRequirementAsync(
    AuthorizationHandlerContext context,
    PermissionsAuthorizationRequirement requirement,
    IEnumerable<PermissionsAuthorizeAttribute> attributes)
{
    // TODO: Check authentication succeeded or not.
    foreach (var permissionAttribute in attributes)
    {
        if (!await Authorize(context, permissionAttribute.RequiredPermissions))
        {
            context.Fail();
            return;
        }
    }
    context.Succeed(requirement);
}

Upvotes: 2

Views: 2025

Answers (1)

Kahbazi
Kahbazi

Reputation: 15015

This class is for Authorization and you can't set 401 status code from here.

This is how things work, you call context.Fail() in your IAuthorizationHandler and then based on whether your request has been authenticated or not PolicyEvaluator will call Forbid or Challenge for that authentication schema.

So you need to have a authentication handler which returns 401 on challenge.

Upvotes: 1

Related Questions