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

Hit*_*esh 9 .net c# azure azure-active-directory

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

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

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

亚太区首席技术官Matt

小智 6

您可以使用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());
}
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*SFT 3

不支持通过 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
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过 REST 执行此操作,它应该如下所示: GET https://graph.windows.net/myorganization/users/ /thumbnailPhoto?api-version=1.5 希望这有帮助,