public async Task <IActionResult> RefreshToken(string sgId) { _logger.LogDebug($"Refresh token has been requested for SGId {sgId}"); var refreshToken = _repository.FindBy <Token>(t => t.User.UserName == sgId) .Include(t => t.User) .ThenInclude(u => u.UserGroups) .ThenInclude(ug => ug.ApplicationUserGroup) .ThenInclude(aug => aug.UserGroupRoles) .ThenInclude(augr => augr.Role) .FirstOrDefault(); if (refreshToken == null || string.IsNullOrEmpty(refreshToken.Value)) { _logger.LogWarning($"Refresh token has not been found for SGId {sgId}"); return(new NotFoundObjectResult($"Refresh token not found for SGID {sgId}")); } var accessTokenResponse = await _oAuthService.RefreshToken(refreshToken.Value); if (accessTokenResponse == null) { return(new BadRequestObjectResult("Cannot refresh token.")); } if (string.IsNullOrWhiteSpace(accessTokenResponse.Refresh_Token)) { _logger.LogWarning($"SGId {sgId} has no refresh token."); } else { refreshToken.Value = accessTokenResponse.Refresh_Token; _repository.Save(); } var tokenInfo = new TokenInfoResponseDto { Access_Token = accessTokenResponse.Access_Token, Expires_In = accessTokenResponse.Expires_In, StGoSGI = sgId }; return(returnTokenAndUserData(tokenInfo, refreshToken.User)); }
private IActionResult returnTokenAndUserData(TokenInfoResponseDto tokenInfo, User user) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, tokenInfo.StGoSGI), new Claim(JwtRegisteredClaimNames.UniqueName, tokenInfo.StGoSGI), new Claim(OAuthClaimNames.AccessToken, tokenInfo.Access_Token) }; var roleClaims = user.UserGroups .Select(ug => ug.ApplicationUserGroup) .SelectMany(aug => aug.UserGroupRoles) .Select(r => new Claim(r.Role.Name, true.ToString())); claims.AddRange(roleClaims); var jwt = _jwtService.CreateJwt(tokenInfo, claims); var token = _jwtService.WriteToken(jwt); // We return user's informations return(new OkObjectResult(new UserAuthenticationDto { UserName = tokenInfo.StGoSGI, FirstName = user.FirstName, LastName = user.LastName, Token = new TokenDto { Value = token, ExpirationDate = jwt.ValidTo }, UserGroup = new UserGroupDto { Roles = user.UserGroups.Select(ug => ug.ApplicationUserGroup) .SelectMany(aug => aug.UserGroupRoles) .Select(r => new RoleDto { Id = r.Role.Id, Name = r.Role.Name } ) } })); }