我正在使用实体框架(Version6.0)应用程序开发一个ASP.NET MVC 5。我增加了简单的谷歌登录,这保存了谷歌电子邮件与用户注册。当Google+用户登录并在视图中进行强制转换时,我如何获得他们的配置文件图片?
发布于 2017-04-30 09:23:47
Google+面向开发人员的API允许您从Google+中获取公共数据。接下来,详细介绍从Google+成功获取公共数据所需执行的所有必要步骤。谷歌暗示着限制Google+ API的使用--每个开发者都有一个配额。我们将在讨论Google控制台时看到这一点。
Google在尝试访问用户数据时使用OAuth2.0协议授权您的应用程序。
它主要采用标准的HTTP方法,通过RESTful API设计来获取和操作用户数据。Google使用JSON数据格式来表示API中的资源。Step1:通过Google控制台生成一个API密钥。Step2:使用GoogleOAuth2AuthenticationOptions,这意味着您需要先在https://console.developers.google.com/project设置一个项目才能获得ClientId和ClientSecret。
在该链接(https://console.developers.google.com/project)中,创建一个项目,然后选择它。然后在左侧菜单上,单击“API& auth”。在“API”下,确保将"Google+ API“设置为"On”。然后单击“凭据”(在左侧菜单中)。然后单击“创建新客户端ID”按钮。按照说明,然后您将得到一个ClientId和ClientSecret,注意两者。
var googleOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = [INSERT CLIENT ID HERE],
ClientSecret = [INSERT CLIENT SECRET HERE],
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
//This following line is need to retrieve the profile image
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));
return Task.FromResult(0);
}
}
};
app.UseGoogleAuthentication(googleOptions);//获取用于配置文件映像请求的访问令牌
var accessToken = loginInfo.ExternalIdentity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault();
Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken);
//request profile image
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(apiRequestUri);
dynamic result = JsonConvert.DeserializeObject(json);
userPicture = result.picture;
}或
var info = await signInManager.GetExternalLoginInfoAsync();
var picture = info.ExternalPrincipal.FindFirstValue("pictureUrl");ExternalLoginCallback方法--我检查使用的是哪个登录提供程序,并处理Google登录的数据。通过链接获取更多信息。https://developers.google.com/identity/protocols/OAuth2
我试过了它的作用。
https://stackoverflow.com/questions/43700504
复制相似问题