2015-04-27 35 views
4

我们已将Azure AD设置为我们应用程序中的身份提供程序。我们要在应用程序中显示应该来自Azuare AD的个人资料图片。我们如何从Azure AD获取个人资料照片?从Azure Active Directory获取个人资料图片

为了测试,我在Azure AD中添加了一个Windows Live Id帐户(具有个人资料图片)。然后,我们使用Graph Explorer尝试了它,但没有运气。

如果有人可以提供一些帮助/示例代码,请提前致谢。

Hitesh

+0

您能否添加更多关于您尝试过以及失败的更多细节? –

+0

只是简单的事情,想要登录的用户资料图片以及其他声明 – Hitesh

+0

您是否有足够的权限访问照片? – Kurkula

回答

2

不支持通过Graph Explorer获取照片。假设“signedInUser”已经包含在用户实体的签名,则使用客户端库此代码段应该为你工作...

 #region get signed in user's photo 
     if (signedInUser.ObjectId != null) 
     { 
      IUser sUser = (IUser)signedInUser; 
      IStreamFetcher photo = (IStreamFetcher)sUser.ThumbnailPhoto; 
      try 
      { 
       DataServiceStreamResponse response = 
       photo.DownloadAsync().Result; 
       Console.WriteLine("\nUser {0} GOT thumbnailphoto", signedInUser.DisplayName); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("\nError getting the user's photo - may not exist {0} {1}", e.Message, 
        e.InnerException != null ? e.InnerException.Message : ""); 
      } 
     } 
     #endregion 

另外,您可以通过REST做到这一点,它应该是这样的: GET https://graph.windows.net/myorganization/users/ /thumbnailPhoto?api-version=1.5 希望这有助于

+0

谢谢丹。只是一个愚蠢的问题,我从哪里得到signedInUser实体? – Hitesh

3

可以使用Azure的Active Directory的图形客户端来获取用户的照片缩略图

var servicePoint = new Uri("https://graph.windows.net"); 
var serviceRoot = new Uri(servicePoint, "<your tenant>"); //e.g. xxx.onmicrosoft.com 
const string clientId = "<clientId>"; 
const string secretKey = "<secretKey>";// ClientID and SecretKey are defined when you register application with Azure AD 
var authContext = new AuthenticationContext("https://login.windows.net/<tenant>/oauth2/token"); 
var credential = new ClientCredential(clientId, secretKey); 
ActiveDirectoryClient directoryClient = new ActiveDirectoryClient(serviceRoot, async() => 
{ 
    var result = await authContext.AcquireTokenAsync("https://graph.windows.net/", credential); 
    return result.AccessToken; 
}); 

var user = await directoryClient.Users.Where(x => x.UserPrincipalName == "<username>").ExecuteSingleAsync(); 
DataServiceStreamResponse photo = await user.ThumbnailPhoto.DownloadAsync(); 
using (MemoryStream s = new MemoryStream()) 
{ 
    photo.Stream.CopyTo(s); 
    var encodedImage = Convert.ToBase64String(s.ToArray()); 
} 

Azure的AD重以二进制格式转换用户的照片,则需要转换为Base64字符串

0

根据Azure AD Graph API Docs,Microsoft建议在Azure AD Graph API逐步淘汰时转换为Microsoft Graph

然而,为了容易抓住经由天青AD的照片,就目前而言,使用这个URL模板:

https://graph.windows.net/myorganization/users/{user_id}/thumbnailPhoto?api-version={version}

例如(这是一个假的用户ID):

https://graph.windows.net/myorganization/users/abc1d234-01ab-1a23-12ab-abc0d123e456/thumbnailPhoto?api-version=1.6

下面的代码假定您已经拥有通过身份验证的用户和令牌。这是一个简单的例子;您需要更改返回值以适应您的需求,添加错误检查等。

const string ThumbUrl = "https://graph.windows.net/myorganization/users/{0}/thumbnailPhoto?api-version=1.6"; 

// Attempts to retrieve the thumbnail image for the specified user, with fallback. 
// Returns: Fully formatted string for supplying as the src attribute value of an img tag. 
private string GetUserThumbnail(string userId) 
{ 
    string thumbnail = "some base64 encoded fallback image"; 
    string mediaType = "image/jpg"; // whatever your fallback image type is 
    string requestUrl = string.Format(ThumbUrl, userId); 

    HttpClient client = new HttpClient(); 
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", GetToken()); 
    HttpResponseMessage response = client.GetAsync(requestUrl).Result; 

    if (response.IsSuccessStatusCode) 
    { 
     // Read the response as a byte array 
     var responseBody = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); 

     // The headers will contain information on the image type returned 
     mediaType = response.Content.Headers.ContentType.MediaType; 

     // Encode the image string 
     thumbnail = Convert.ToBase64String(responseBody); 
    } 

    return $"data&colon;{mediaType};base64,{thumbnail}"; 
} 

// Factored out for use with other calls which may need the token 
private string GetToken() 
{ 
    return HttpContext.Current.Session["Token"] == null ? string.Empty : HttpContext.Current.Session["Token"].ToString(); 
} 
相关问题