从 Azure Active Directory 获取个人资料图片

Posted

技术标签:

【中文标题】从 Azure Active Directory 获取个人资料图片【英文标题】:Get profile picture from Azure Active Directory 【发布时间】:2015-04-27 12:05:17 【问题描述】:

我们已将 Azure AD 设置为应用程序中的身份提供者。我们希望在应用程序中显示应该来自 Azure AD 的个人资料图片。

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

我们如何从 Azure AD 中获取个人资料图片?

【问题讨论】:

您能否详细说明您尝试了什么以及如何失败? 只是简单的事情,想要登录的用户个人资料图片以及其他声明 您是否有足够的权限访问照片? 【参考方案1】:

您可以使用 Azure Active Directory Graph Client 获取用户缩略图照片

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 字符串

【讨论】:

【参考方案2】:

不支持通过 Graph Explorer 获取照片。假设“signedInUser”已经包含登录的用户实体,那么这个使用客户端库的代码 sn-p 应该适合你......

        #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 希望这会有所帮助,

【讨论】:

谢谢丹。只是一个愚蠢的问题,我从哪里获得 signedInUser 实体? 完整解释:developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/…【参考方案3】:

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

但是,要通过 Azure 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();

【讨论】:

以上是关于从 Azure Active Directory 获取个人资料图片的主要内容,如果未能解决你的问题,请参考以下文章

从 Azure Active Directory 验证 JWT

从 Powershell 获取 Azure Active Directory 访问令牌

从 Azure Active Directory Graph 迁移到 Microsoft Graph

从 Azure Active Directory 获取个人资料图片

您如何从 Azure Active Directory 中获取搭建的 Weather Forecast Api 将接受的访问令牌?

访问Azure Active Directory用户和角色