public async Task <IActionResult> Authenticate(string authorizationCode) { _logger.LogDebug($"Authentication requested with authorization code {authorizationCode}"); var accessTokenResponse = await _oAuthService.ValidateAuthoriztionCode(authorizationCode); if (accessTokenResponse == null) { _logger.LogError($"Validation of authorization code failed for code {authorizationCode}."); return(new UnauthorizedResult()); } var tokenInfoResponse = await _oAuthService.GetTokenInfo(accessTokenResponse.Access_Token); if (tokenInfoResponse == null) { _logger.LogError($"Unable to get token info for code {authorizationCode}."); return(new UnauthorizedResult()); } _logger.LogDebug($"Retrieved SGId: {tokenInfoResponse.StGoSGI}"); var user = _repository.FindBy <User>(u => u.UserName == tokenInfoResponse.StGoSGI) .Include(u => u.Token) .Include(u => u.UserGroups) .ThenInclude(ug => ug.ApplicationUserGroup) .ThenInclude(aug => aug.UserGroupRoles) .ThenInclude(augr => augr.Role) .FirstOrDefault(); if (user == null) { _logger.LogWarning($"SGId {tokenInfoResponse.StGoSGI} has not been found in the database"); return(new NotFoundObjectResult($"User with SGID {tokenInfoResponse.StGoSGI} doesn't exist in the database.")); } if (string.IsNullOrWhiteSpace(accessTokenResponse.Refresh_Token)) { _logger.LogWarning($"SGId {tokenInfoResponse.StGoSGI} has no refresh token."); } else { if (user.Token == null) { user.Token = new Token(); } user.Token.Value = accessTokenResponse.Refresh_Token; _repository.Save(); } return(returnTokenAndUserData(tokenInfoResponse, user)); }