使用 asp.net MVC 通过 Google 重定向 URI

问题描述 投票:0回答:2

我正在尝试在 ASP.NET MVC 5 中将 oauth 与 Google 一起使用。

在 Google 的开发者控制台中,我输入了重定向 uri:

www.mydomain.com/account/externallogincallback

并认为这样就可以了。但事实并非如此。

我输入:

www.mydomain.com/signin-google

并且成功了!

我尝试在我的项目中搜索字符串“signin-google”,但在任何地方都找不到它。

有人可以告诉我发生了什么事吗?为什么会这样?谢谢。

c# asp.net-mvc oauth-2.0 google-authentication
2个回答
8
投票

我懒得写一个格式正确的答案,我将这些注释放在代码中,以便自己记住如何解决这个问题。这并不是一个真正的问题,只是我从来没有费心去正确阅读的东西:)但这就是你可以做的让它发挥作用。有两种方法可以选择。我已经尝试过这两个选项,并且两个选项都工作得很好。我现在选择第一个,这真的不重要。这是我在 Startup.Auth.cs 文件中的评论。

// My notes to resolve Google Error: redirect_uri_mismatch error
// By default GoogleOAuth2AuthenticationOptions has CallbackPath defined as "/signin-google"
// https://msdn.microsoft.com/en-us/library/microsoft.owin.security.google.googleoauth2authenticationoptions(v=vs.113).aspx
// But the real path should be Controller/Action: for this application it is "/Account/ExternalLoginCallback"

// There are 2 ways to define it properly:
// 1) Add a new route in RouteConfig.cs that will map "/signin-google" into "/Account/ExternalLoginCallback":
// routes.MapRoute(name: "signin-google", url: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallback" });
// Remember, in Google Developers Console you must have your "/signin-google" redirect URI, since that is what your app sends to Google

// 2) Completely overwrite built-in "/signin-google" path.
// Owerwrite CallbackPath right here by adding this line after ClientSecret:
// CallbackPath = new PathString("/Account/ExternalLoginCallback")
// Remember, in Google Developers Console you must have "/Account/ExternalLoginCallback" redirect URI, since now that is what your app sends to Google

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "xxxxxxxxxxxxxxxxxxxx",
    ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx"
});

0
投票
  1. googleOptions.CallbackPath
    用于 .NET 中的 OAuth 中间件,用于在用户通过身份验证后侦听来自 Google 的响应。
  2. signin-google
    的默认值,如上面的答案和此处的文档所述:https://learn.microsoft.com/en-us/previous-versions/aspnet/dn800251(v=vs.113)
  3. 令人困惑的是,在 Google Console 中,这被称为
    Authorized redirect URIs
    。但在 .NET 中,这称为
    googleOptions.CallbackPath
  4. 在添加 Google-Signin API 的情况下,我还添加了一个
    .NET RedirectUri
    由这个
    Google callBack Path
    调用。这是
    .NET RedirectUri
    googleOptions.CallbackPath
    不同,不需要在 Google Console 上列入白名单。
  5. 而且每次在 Google Console 中更新
    Authorized redirect URIs
    ,都需要几分钟才能生效。
© www.soinside.com 2019 - 2024. All rights reserved.