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 Unauthorised_Should_Return_Correctly() { var message = "message"; var actual = ApiResponseHelper.Unauthorised(message); actual.Should().BeOfType <ActionResult <ApiResponse> >(); actual.Result.Should().BeOfType <ObjectResult>(); actual.Result.As <ObjectResult>().StatusCode.Should().Be(StatusCodes.Status401Unauthorized); 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(); }