如何在MVC中用应用程序登录后获取微软账号头像 [英] How to get microsoft account profile photo after login with application in mvc

查看:34
本文介绍了如何在MVC中用应用程序登录后获取微软账号头像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

claimprincipal的帮助下,我可以获得登录用户的详细信息,如下所示,但它不像Google那样提供任何图片相关信息:

https://apis.live.net/v5.0/{USER_ID}/picture?type=large

表示URL包含路径'{user_id}',这是不受支持的。 已尝试

https://graph.microsoft.com/v1.0/me/photo/$value

它请求访问令牌,但我不确定必须传递什么

string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

需要添加到任何Outlook帐户中的图像

推荐答案

要显示的图像..我们必须使用承载令牌,并且必须将图像转换为内存流,然后才能使用它。我用下面的方法做了这件事。希望对您有所帮助.

 var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
                        var request = new RestRequest(Method.POST);
                        request.AddHeader("cache-control", "no-cache");
                        request.AddHeader("content-type", "application/x-www-form-urlencoded");
                        request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
                        IRestResponse response = client.Execute(request);
                        Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);

                        var Token = jsonContent.AccessToken;
                        var TokenType = jsonContent.TokenType;
                        HttpClient httpClient = new HttpClient();
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                        HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
                        if (response1.StatusCode == HttpStatusCode.OK)
                        {
                            using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
                            {
                                MemoryStream ms = new MemoryStream();
                                responseStream.CopyTo(ms);
                                byte[] buffer = ms.ToArray();
                                string result = Convert.ToBase64String(buffer);
                                HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
                                responseStream.Close();
                            }
                        }

这篇关于如何在MVC中用应用程序登录后获取微软账号头像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆