使用HttpContext测试AuthorizationHandler

时间:2019-05-16 14:55:03

标签: c# asp.net-core

我正在测试自定义的AuthorizationHandlers,但是当我获得HttpContext时,它为null。

        private IAuthorizationService BuildAuthorizationService(Action<IServiceCollection> setupServices = null)
        {
            var services = new ServiceCollection();
            services.AddAuthorization();
            services.AddOptions();
            services.AddLogging();

            setupServices?.Invoke(services);
            return services.BuildServiceProvider().GetRequiredService<IAuthorizationService>();
        }
        [Fact]
        public async Task ShouldAllowIfScopeClaimWorkflowAdminIsPresent()
        {
            // Arrange
            var authorizationService = BuildAuthorizationService(services =>
            {
                services.AddSingleton<IAuthorizationHandler, Jarvis.Security.Handlers.ModulePermissionHandlers>();
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("SomePolicyName",
                        policy => policy.Requirements.Add(new Jarvis.Security.Handlers.PermissionRequirement()));
                });
            });
            var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim("Issuer", "WebApplication1") }));

            // Act
            var allowed = await authorizationService.AuthorizeAsync(user, "SomePolicyName");

            // Assert
            Assert.True(allowed.Succeeded);
        }
    }
\\\Hanlder
 protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            var ctx = (AuthorizationFilterContext)context.Resource;
            var intention = ctx.HttpContext.Request.Method;
            var resource = ctx.RouteData.Values["controller"].ToString();

            if (context.User.HasClaim(c => c.Issuer == resource))
                context.Succeed(requirement);

            return Task.CompletedTask;
        }

当我想获取var意图= ctx.HttpContext.Request.Method; 它为空:/ 任何建议

0 个答案:

没有答案