【发布时间】:2022-11-08 22:20:02
【问题描述】:
我试图使用谷歌身份验证扩展从Microsoft.Owin.Security.Google
包在 MVC5 程序中。这是我的 StartUp.cs :
var googlePlusOptions = new GoogleOAuth2AuthenticationOptions {};
googlePlusOptions.ClientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com";
googlePlusOptions.AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth";
googlePlusOptions.TokenEndpoint = "https://oauth2.googleapis.com/token";
googlePlusOptions.ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
googlePlusOptions.CallbackPath = new PathString("/GoogleLoginCallback");
app.UseGoogleAuthentication(googlePlusOptions);
和 LoginController 内的 SignInMethod 方法:
[HttpGet]
[AllowAnonymous]
public void SignInGoogle(string ReturnUrl = "/", string type = "")
{
if (!Request.IsAuthenticated)
{
if (type == "Google")
{
var owinContext = HttpContext.GetOwinContext();
owinContext.Authentication.Challenge(new AuthenticationProperties { RedirectUri = "Login/GoogleLoginCallback" }, "Google");
Response.StatusCode = 401;
Response.End();
}
}
}
和 CallBack Url 在同一个控制器中:
[AllowAnonymous]
public ActionResult GoogleLoginCallback()
{
var claimsPrincipal = HttpContext.User.Identity as ClaimsIdentity;
var loginInfo = GoogleLoginViewModel.GetLoginInfo(claimsPrincipal);
if (loginInfo == null)
{
return RedirectToAction("Index");
}
var user = db.UserAccounts.FirstOrDefault(x => x.Email == loginInfo.emailaddress);
if (user == null)
{
user = new UserAccount
{
Email = loginInfo.emailaddress,
GivenName = loginInfo.givenname,
Identifier = loginInfo.nameidentifier,
Name = loginInfo.name,
SurName = loginInfo.surname,
IsActive = true
};
db.UserAccounts.Add(user);
db.SaveChanges();
}
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, user.Email),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Email, user.Email),
// optionally you could add roles if any
new Claim(ClaimTypes.Role, "User")
},
CookieAuthenticationDefaults.AuthenticationType);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return Redirect("~/");
}
现在程序进入谷歌的登录屏幕,但当它回到回调网址时
登录信息一片空白。这是来自 Call Back Url 的响应:
到目前为止我所做的事情没有任何结果: 1-激活 Google+ API 2-将nuget更新到最新版本(4.2 atm) 3-将电子邮件添加到 TestUser 或将谷歌控制台内的项目更改为生产 4-在谷歌控制台中添加并填写同意部分 5-将js回调设置为空白
有点奇怪的一件事是,如果我修改 ClientId,谷歌的登录屏幕会阻止我,但如果我更改 secretId,什么都不会发生,但我仍然看到上面的错误。 我今天从 OAuth 控制台面板中获得了它们(ClientId,SecretId)。
【问题讨论】:
标签: asp.net-mvc google-api-dotnet-client