public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } // Allow Anonymous skips all authorization var hasAnonymousFilter = context.Filters.OfType <IAllowAnonymousFilter>().Any(); var hasAnonymouseAttribute = context.ActionDescriptor.EndpointMetadata.OfType <AllowAnonymousAttribute>().Any(); if (hasAnonymousFilter || hasAnonymouseAttribute) { return; } var policyEvaluator = context.HttpContext.RequestServices.GetRequiredService <IPolicyEvaluator>(); var authenticateResult = await policyEvaluator.AuthenticateAsync(Policy, context.HttpContext); var authorizeResult = await policyEvaluator.AuthorizeAsync(Policy, authenticateResult, context.HttpContext, context); if (authorizeResult.Challenged) { context.Result = ApiResponseHelper.Unauthorised("Unauthorised.").Result; } else if (authorizeResult.Forbidden) { context.Result = ApiResponseHelper.Forbidden("Forbidden.", Policy.AuthenticationSchemes.ToArray()).Result; } }
public void Forbidden_Should_Return_Correctly() { var message = "message"; var actual = ApiResponseHelper.Forbidden(message); actual.Should().BeOfType <ActionResult <ApiResponse> >(); actual.Result.Should().BeOfType <ObjectResult>(); actual.Result.As <ObjectResult>().StatusCode.Should().Be(StatusCodes.Status403Forbidden); actual.Result.As <ObjectResult>().Value.Should().BeOfType <ApiResponse>(); actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Success.Should().Be(false); actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Message.Should().Be(message); actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Data.Should().BeNull(); }