我试图在MVC 5网络应用中实施Google身份验证。身份验证工作正常,但我会检索配置文件和图片信息。
为此,我添加了一个GoogleOAuth2AuthenticationOptions对象来指定其他声明:
var googleOAuth2AuthenticationOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "xxxxxxxxxxxxxxxx",
ClientSecret = "xxxxxxxxxxxxxxxxx",
CallbackPath = new PathString("/Account/LoginCallback"),
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString()));
context.Identity.AddClaim(new Claim("profile", context.User.GetValue("profile").ToString()));
}
}
};
app.UseGoogleAuthentication(googleOAuth2AuthenticationOptions);
但它会导致生成错误的网址:
没有'?'在参数之前,这会导致redirect_uri_mismatch。
然而,当我简单地使用时:
app.UseGoogleAuthentication(
clientId : "xxxxxxxxxxxxxxxxxxx",
clientSecret : "xxxxxxxxxxxxxxxxx");
它在工作。
有什么想法吗?
答案 0 :(得分:5)
只使用这么多。
var googleOAuth2AuthenticationOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "MYCLIENTID",
ClientSecret = "MYSECRET",
};
app.UseGoogleAuthentication(googleOAuth2AuthenticationOptions);
此方法似乎会在地址中自动使用signin-google请求。要修复谷歌控制台中此更改谷歌回调位置以指向此地址。
添加 RouteConfig文件
routes.MapRoute( name: "signin-google", url: "signin-google", defaults: new { controller = "Account", action = "LoginCallback" } );
答案 1 :(得分:1)
使用此代码片段工作正常,只需替换ClientID,ClientSecret将为您工作。
var googleOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
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);
如果仍然存在错误
假设您的应用程序URI如下所示
然后在console.developers.google.com上,您注册的URI需要更改,如下所示。
只需在结尾处的URI中添加[ signin-google ]
http://localhost:2625/signin-google
最后保存它。