Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Azure Active Directory获取配置文件图片_C#_.net_Azure_Azure Active Directory - Fatal编程技术网

C# 从Azure Active Directory获取配置文件图片

C# 从Azure Active Directory获取配置文件图片,c#,.net,azure,azure-active-directory,C#,.net,Azure,Azure Active Directory,我们已将Azure广告设置为应用程序中的身份提供商。我们希望在应用程序中显示来自Azure广告的个人资料图片 为了测试,我在Azure广告中添加了一个Windows Live Id帐户(有个人资料图片)。然后我们使用图形浏览器进行了尝试,但没有成功 如何从Azure AD获取个人资料图片?不支持通过图形浏览器获取照片。假设“SignedUser”已经包含登录用户实体,那么这个使用客户端库的代码段应该适合您 #region get signed in user's photo

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

为了测试,我在Azure广告中添加了一个Windows Live Id帐户(有个人资料图片)。然后我们使用图形浏览器进行了尝试,但没有成功


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

不支持通过图形浏览器获取照片。假设“SignedUser”已经包含登录用户实体,那么这个使用客户端库的代码段应该适合您

        #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执行此操作,它应该如下所示: 获取/缩略图照片?api版本=1.5
希望这有帮助,

您可以使用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());
}
var servicePoint=新Uri(“https://graph.windows.net");
var serviceRoot=新Uri(servicePoint,“”)//e、 g.xxx.onmicrosoft.com
常量字符串clientId=“”;
常量字符串secretKey=“”;//ClientID和SecretKey是在向Azure AD注册应用程序时定义的
var authContext=新的AuthenticationContext(“https://login.windows.net//oauth2/token");
var-credential=新的ClientCredential(clientId,secretKey);
ActiveDirectoryClient directoryClient=新的ActiveDirectoryClient(serviceRoot,异步()=>
{
var result=await authContext.AcquireTokenAsync(“https://graph.windows.net/“,凭证);
返回result.AccessToken;
});
var user=wait directoryClient.Users.Where(x=>x.UserPrincipalName==“”)。ExecuteSingleAsync();
DataServiceStreamResponse photo=wait user.ThumbnailPhoto.DownloadAsync();
使用(MemoryStream s=new MemoryStream())
{
photo.Stream.CopyTo(s);
var encodedImage=Convert.ToBase64String(s.ToArray());
}
Azure AD以二进制格式返回用户的照片,由于Azure AD Graph API正在逐步淘汰,您需要根据Microsoft建议转换为Base64字符串

但是,要通过Azure广告轻松抓取照片,请使用以下URL模板:

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

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

https://graph.windows.net/myorganization/users/abc1d234-01ab-1a23-12ab-abc0d123e456/thumbnailPhoto?api-版本=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();
}

你能添加更多关于你到底尝试了什么以及如何失败的细节吗?很简单,想和其他要求一起登录用户档案图片吗?你有足够的权限访问照片吗?谢谢Dan。只有一个愚蠢的问题,我从哪里获得SignedUser实体?完整解释: