protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string errorReason; if (!Context.Request.Headers.TryGetValue(Options.AuthorizationHeader, out StringValues headerValue)) { errorReason = $"Missing or malformed '{Options.AuthorizationHeader}' header."; return(await Task.FromResult(AuthenticateResult.Fail(errorReason))); } var authorizationHeader = headerValue.First(); if (!authorizationHeader.StartsWith(Options.SignInScheme + ' ', StringComparison.OrdinalIgnoreCase)) { errorReason = "Malformed 'Authorization' header."; return(await Task.FromResult(AuthenticateResult.Fail(errorReason))); } try { string token = authorizationHeader.Substring(SignInScheme.Length).Trim(); var jwtValidationResult = _jwtHandler.Validate(token); if (jwtValidationResult.Succeeded) { var jwtPayLoad = jwtValidationResult.JwtPayLoad; long.TryParse(jwtPayLoad.Id, out var userId); var user = await _userManager.FindByIdAsync(userId); if (user == null) { errorReason = "User Not Found"; return(await Task.FromResult(AuthenticateResult.Fail(errorReason))); } if (!await _userManager.IsUserActiveAsync(user)) { errorReason = "User Not Active"; return(await Task.FromResult(AuthenticateResult.Fail(errorReason))); } var claims = new List <Claim>() { new Claim(ClaimTypes.Authentication, Options.Authentication), new Claim("Token", token), new Claim("Sub", jwtPayLoad.Id), new Claim(ClaimTypes.Name, jwtPayLoad.Id), new Claim(ClaimTypes.NameIdentifier, user.Username) }; var id = new ClaimsIdentity(claims, Options.SignInScheme); var identity = new ClaimsIdentity(id); Options.Identity = identity; var result = Task.FromResult( AuthenticateResult.Success( new AuthenticationTicket( new ClaimsPrincipal(Options.Identity), new AuthenticationProperties(), Scheme.Name))); return(await result); } errorReason = string.Join("; ", jwtValidationResult.Errors); return(await Task.FromResult(AuthenticateResult.Fail(errorReason))); } catch (Exception e) { Logger.LogError(e, e.Message); return(await Task.FromResult(AuthenticateResult.Fail(e))); } }