授权过滤器测试失败的 webapi

Authorization filter test failed webapi

我正在为授权过滤器编写单元测试以验证请求/令牌。但是,它 return 无效。不知道哪里出了问题。

https://programmium.wordpress.com/2020/04/30/unit-testing-custom-authorization-filter-in-net-core/

public class UserAuthorizationTests
{
    private readonly Mock<ILogger<UserAuthorizationFilter>> _mocklogger;
    private readonly Mock<IOptions<UserAuthorisationOptions>> _mockOption;
    public UserAuthorizationTests()
    {
         _mocklogger = new Mock<ILogger<UserAuthorizationFilter>>();
         _mockOption = new Mock<IOptions<UserAuthorisationOptions>>(); 
    }
    
    [Fact]
    public void UserAuthorizationTest()
    {
        var httpContextMock = new Mock<HttpContext>();
        httpContextMock.Setup(a => a.Request.Headers["UserAuthorization"]).Returns("test");
        
        ActionContext fakeActionContext =
            new ActionContext(httpContextMock.Object, 
                new Microsoft.AspNetCore.Routing.RouteData(), 
                new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor());            
            
        AuthorizationFilterContext fakeAuthFilterContext =
            new AuthorizationFilterContext(fakeActionContext, 
                new List<IFilterMetadata>());
        
        UserAuthorizationFilter userAuthorizationFilter = 
            new UserAuthorizationFilter(_mockOption.Object, _mocklogger.Object);
        userAuthorizationFilter.OnAuthorization(fakeAuthFilterContext);
        
        Assert.NotEqual(typeof(UnauthorizedResult), userAuthorizationFilter.GetType());
    }
}

你说的是“它return null”,如果你能描述得更清楚一些可能会有所帮助

我使用 Moq 编写了 xunit 测试,如下所示:

            var httpContextMock = new Mock<HttpContext>();
            httpContextMock.Setup(a => a.Request.Headers["Authorization"]).Returns("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiSmVmZmNreSIsIm5iZiI6MTY1MjA4NTg1NSwiZXhwIjoxNjUyMDg2MTU1LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjUwMDEifQ.cOpCN93U108Xr_km7GunxAJMrqx3LPnYAl3gLnXDW5M");            
            ActionContext fakeActionContext =new ActionContext(httpContextMock.Object,  new Microsoft.AspNetCore.Routing.RouteData(),
                                             new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor());
            JwksFilter jwksfilter = new JwksFilter();
            AuthorizationFilterContext fakeAuthFilterContext =new AuthorizationFilterContext(fakeActionContext, new List<IFilterMetadata>() {  }); 

            jwksfilter.OnAuthorization(fakeAuthFilterContext);    

            Assert.Equal(typeof(UnauthorizedResult), fakeAuthFilterContext.Result.GetType());

我的过滤器中的代码:

public void OnAuthorization(AuthorizationFilterContext context)
        {
            var jwks = context.HttpContext.Request.Headers["Authorization"].ToString();
            
            var validateParameters = new TokenValidationParameters() 
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890123456")),
                ValidateIssuer = true,
                ValidIssuer = "http://localhost:5000",
                ValidateAudience = true,
                ValidAudience = "http://localhost:5001",
                ValidateLifetime = true,
                ClockSkew = TimeSpan.FromMinutes(5)
            };
            var valiresult = ValidateToken(jwks, validateParameters);
            if (valiresult == false)
            {                   
                context.Result = new UnauthorizedResult();                   
            }
        }
        private static bool ValidateToken(string token, TokenValidationParameters validationParameters)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            try
            {
                tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

结果: