/// <summary> /// ToEmail: Gets the email for the graph user /// </summary> /// <param name="graphUser">graph user</param> /// <returns>returns email id</returns> public static string ToEmail(Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser) { if (!string.IsNullOrWhiteSpace(graphUser.Mail)) { return(graphUser.Mail); } return(graphUser.OtherMails != null?graphUser.OtherMails.FirstOrDefault() : graphUser.UserPrincipalName); }
/// <summary> /// Gets Graphical User /// </summary> /// <param name="loginInfo">login information</param> /// <param name="userCacheKey">User Cache key value</param> /// <param name="userAuthResultCacheKey">User authentication cache key</param> /// <returns>User value</returns> private async Task <Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo, string userCacheKey, string userAuthResultCacheKey) { var client = this.GetGraphClient(loginInfo, PortalSettings.Instance.Authentication.RootUrl, PortalSettings.Instance.Authentication.TenantId); Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null; // retry tokenRetryCount times to retrieve the users. each time it fails, it will nullify the cache and try again for (var x = 0; x < TokenRetryCount; x++) { try { ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Attempting to retrieve user from Graph with NameIdentifier {loginInfo.Login.ProviderKey}."); // when we call this, the client will try to retrieve a token from GetAuthTokenTask() user = await client.Me.ExecuteAsync(); // if we get here then everything is alright. stop looping break; } catch (AggregateException ex) { var handled = false; foreach (var innerEx in ex.InnerExceptions) { if (innerEx.InnerException == null) { break; } // if the exception can be cast to a DataServiceClientException // NOTE: the version of Microsoft.Data.Services.Client MUST match the one Microsoft.Azure.ActiveDirectory.GraphClient uses (currently 5.6.4.0. 5.7.0.0 won't cast the exception correctly.) var clientException = innerEx.InnerException as DataServiceClientException; if (clientException?.StatusCode == (int)HttpStatusCode.Unauthorized) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Current GraphClient auth token didn't seem to work. Discarding..."); // the token didn't seem to work. throw away cached token to retrieve new one this.HttpContext.Cache.Remove(TokenCacheKey); handled = true; } } if (!handled) { throw; } } } // if users is null here, we have a config problem where we can't get correct auth tokens despite repeated attempts if (user == null) { this.OutputGraphError(Enums.AzureADGraphAuthResults.AuthConfigProblem, userAuthResultCacheKey, loginInfo); return(null); } // add cache entry for graph user object. it will expire in GraphCacheTtlMinutes minutes HttpRuntime.Cache.Add(userCacheKey, user, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null); return(user); }