public async Task HandleAsync(AuthorizationHandlerContext context) { var httpContext = _contextAccessor.HttpContext; var authHeader = httpContext.Request.Headers["Authorization"].ToString(); if (authHeader != null && authHeader.StartsWith("bearer", StringComparison.OrdinalIgnoreCase)) { var tokenStr = authHeader.Substring("Bearer ".Length).Trim(); try { var signature = _jwtTokenHelper.GetSignature(tokenStr); var isRegistered = await _tokenProvider.IsAccessTokenRegistered(signature); if (!isRegistered) { context.Fail(); } } catch (Exception e) { _logger.LogError(e, e.Message); context.Fail(); } } }
public async Task <IActionResult> SignIn([FromBody] LoginViewModel loginViewModel) { var user = await _userManager.FindByEmailAsync(loginViewModel.Email); if (user == null) { return(new NotFoundResult()); } var result = await _signInManager.CheckPasswordSignInAsync(user, loginViewModel.Password, false); if (result.Succeeded) { var token = new JwtTokenViewModel { AccessToken = _jwtTokenGenerator.Generate(user), RefreshToken = _refreshTokenGenerator.Generate() }; try { await _tokenProvider.RegisterRefreshToken(token.RefreshToken, user.Id); await _tokenProvider.RegisterAccessToken( _jwtTokenHelper.GetSignature(token.AccessToken), _jwtTokenHelper.GetExpirationDate(token.AccessToken), user.Id); } catch (Exception) { return(new StatusCodeResult((int)HttpStatusCode.InternalServerError)); } return(new OkObjectResult(token)); } if (result.IsLockedOut || result.IsNotAllowed) { return(new ForbidResult()); } return(new ForbidResult()); }
public async Task <IActionResult> RefreshAccessToken(Guid refreshToken) { var refreshTokenObject = await _tokenProvider.GetRefreshToken(refreshToken); if (refreshTokenObject == null) { return(BadRequest()); } var user = await _userManager.FindByIdAsync(refreshTokenObject.UserId.ToString()); if (user == null) { return(BadRequest()); } var token = new JwtTokenViewModel { AccessToken = _tokenGenerator.Generate(user), RefreshToken = refreshToken.ToString() }; try { await _tokenProvider.UpdateRefreshToken(refreshToken); await _tokenProvider.RegisterAccessToken( _jwtTokenHelper.GetSignature(token.AccessToken), _jwtTokenHelper.GetExpirationDate(token.AccessToken), user.Id); } catch (Exception) { return(new StatusCodeResult((int)HttpStatusCode.InternalServerError)); } return(new OkObjectResult(token)); }