public override void OnActionExecuting(ActionExecutingContext context) { if (!_authOptions.AuthHeaderCheckEnabled) { return; } var logger = context.HttpContext.RequestServices.GetService <ILogger <DiagnosticKeysController> >(); try { string authHeader = context.HttpContext.Request.Headers["Authorization"]; if (authHeader != null && authHeader.Contains("Bearer")) { var token = authHeader.Replace("Bearer", ""); _jwtValidationService.IsTokenValid(token); return; } else { logger.LogWarning("Missing token or invalid scheme. Header value:" + authHeader); context.Result = new UnauthorizedObjectResult("Missing token or invalid scheme."); } } catch (Exception e) { logger.LogError("Error on authorization:" + e); context.Result = new UnauthorizedObjectResult(e.Message); } }
public override async void OnActionExecuting(ActionExecutingContext context) { var logger = context.HttpContext.RequestServices.GetService <ILogger <DiagnosticKeysController> >(); try { string authHeader = context.HttpContext.Request.Headers["Authorization"]; if (authHeader != null && authHeader.Contains("Bearer")) { var token = authHeader.Replace("Bearer", string.Empty); token = token.Trim(); _jwtValidationService.IsTokenValid(token); return; } if (_anonymousTokenConfig.Enabled) { if (authHeader != null && authHeader.StartsWith("Anonymous ")) { var anonymousToken = authHeader.Replace("Anonymous ", string.Empty); var isValid = await _anonymousTokenValidationService.IsTokenValid(anonymousToken); if (!isValid) { context.Result = new UnauthorizedObjectResult("Invalid token"); } return; } } logger.LogWarning("Missing token or invalid scheme. Header value:" + authHeader); context.Result = new UnauthorizedObjectResult("Missing token or invalid scheme."); } catch (Exception e) { logger.LogError("Error on authorization:" + e); context.Result = new UnauthorizedObjectResult(e.Message); } }
public void TestValidateToken_WithValidToken() { var validationResult = _jwtValidationService.IsTokenValid(ValidToken); validationResult.Should().BeTrue(); }