从Azure Active Directory获取个人资料图片 [英] Get profile picture from Azure Active Directory
问题描述
我们已在应用程序中将Azure AD设置为身份提供者.我们想要在应用程序中显示应该来自Azure AD的配置文件图片.
We have set the Azure AD as a identity provider in our application. We want to display profile picture that should come from Azure AD, in the application.
为了进行测试,我在Azure AD中添加了一个Windows Live ID帐户(具有个人资料图片).然后,我们使用Graph Explorer进行了尝试,但是没有运气.
In order to test, I have added one Windows Live Id account (which has a profile picture) in the Azure AD. We then tried it using Graph Explorer, but no luck.
我们如何从Azure AD获取个人资料图片?
How do we get the profile picture from Azure AD?
推荐答案
您可以使用Azure Active Directory Graph Client获取用户缩略图
You can use Azure Active Directory Graph Client to get user thumbnail photo
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字符串
Azure AD returns user's photo in binary format, you need to convert to Base64 string
这篇关于从Azure Active Directory获取个人资料图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!