protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (AuthenticationHeaderValue.TryParse(Request.Headers["Authorization"], out AuthenticationHeaderValue authHeader)) { try { if (string.IsNullOrEmpty(authHeader?.Parameter) || !authHeader.Scheme.Equals("Bearer", StringComparison.OrdinalIgnoreCase)) { return(AuthenticateResult.Fail("Invalid Authorization Header")); } var jwtTokenString = authHeader.Parameter; var token = _tokenService.Read(jwtTokenString); var account = await _accountService.GetByUsernameAsync(GetEmailFromClaims(token.Claims)); if (account == null) { return(AuthenticateResult.Fail("User not found")); } var principal = _tokenService.Validate(jwtTokenString); if (principal == null) { return(AuthenticateResult.Fail("Token validation failed")); } return(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name))); } catch (Exception ex) { return(AuthenticateResult.Fail(ex.Message)); } } return(AuthenticateResult.Fail("Missing Authorization Header")); }