public async Task TestInternalAuth(string goodKey, string requestKey, bool valid) { var options = new CrpcOptions { InternalKeys = new string[] { goodKey }, }; var middleware = new AuthMiddleware(_loggerFactory, Options.Create(options)); var context = new DefaultHttpContext(); middleware.SetAuthentication(AuthenticationType.AllowInternalAuthentication); context.Request.Headers.Add("Authorization", $"bearer {requestKey}"); if (valid) { await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask); return; } var ex = await Assert.ThrowsAsync <CrpcException>(async() => { await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask); }); Assert.Equal(CrpcCodes.Unauthorized, ex.Message); }
public async void ShouldInvalidate_WhenApiKeyIsNull() { RequestDelegate next = (HttpContext context) => Task.CompletedTask; var context = new DefaultHttpContext(); var authMiddleware = new AuthMiddleware(next); await authMiddleware.InvokeAsync(context, _mockAuthService.Object); context.Response.StatusCode.Should().Be((int)HttpStatusCode.Unauthorized); }
public async void ShouldAssignIdentity_WhenApiKeyIsValid() { _mockAuthService.Setup(service => service.GetUserIdByToken(It.IsAny <string>())).Returns(Task.FromResult((int?)1)); RequestDelegate next = (HttpContext context) => Task.CompletedTask; var context = new DefaultHttpContext(); context.Request.Headers.Add("X-API-Key", "foobar"); var authMiddleware = new AuthMiddleware(next); await authMiddleware.InvokeAsync(context, _mockAuthService.Object); context.User.Identity.Name.Should().Be("1"); }
public async void ShouldInvalidate_WhenApiKeyIsInvalid() { _mockAuthService.Setup(service => service.GetUserIdByToken(It.IsAny <string>())).Returns(Task.FromResult <int?>(null)); RequestDelegate next = (HttpContext context) => Task.CompletedTask; var context = new DefaultHttpContext(); context.Request.Headers.Add("X-API-Key", "foobar"); var authMiddleware = new AuthMiddleware(next); await authMiddleware.InvokeAsync(context, _mockAuthService.Object); context.Response.StatusCode.Should().Be(401); }
public async Task TestUnsafeNoAuth(string key) { var options = new CrpcOptions { InternalKeys = new string[] { key }, }; var middleware = new AuthMiddleware(_loggerFactory, Options.Create(options)); var context = new DefaultHttpContext(); middleware.SetAuthentication(AuthenticationType.UnsafeNoAuthentication); context.Request.Headers.Add("Authorization", $"bearer {key}"); await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask); }
public async Task TestNoAuthenticationTypeSet() { var options = new CrpcOptions(); var middleware = new AuthMiddleware(_loggerFactory, Options.Create(options)); var context = new DefaultHttpContext(); context.Response.Body = new MemoryStream(); var ex = await Assert.ThrowsAsync <InvalidOperationException>(async() => { await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask); }); Assert.Equal("Authentication type not set", ex.Message); }