繁体   English   中英

Google oauth2 api 客户端无法正常工作

[英]Google oauth2 api client is not working properly

我的 grails 2.3.4 的控制器操作中有一些代码使用 google java 客户端库来访问 OAuth2 api。 但是当我创建一个 GoogleAuthorizationCodeFlow 的实例时,我收到了 redirect_uri_mismatch 错误。 谷歌给我的网址是http://localhost:60720/Callback ,而我在谷歌 API 控制台中将回调网址定义为http://localhost:8080/<myAppName>/<controllerName>/<actionName> . 当我在地址栏中手动复制粘贴我的重定向网址时,替换了谷歌给我的网址,我的应用程序运行良好。

我已将该应用程序注册为 Web 应用程序,但未在 api 控制台中安装应用程序。 我能做什么? 请帮忙。 如果我无法解决这个问题,那么我将恢复到 REST Api。

ResourceLocator grailsResourceLocator



JsonFactory jsonFactory = JacksonFactory.defaultInstance

File clientSecretsFile = grailsResourceLocator.findResourceForURI("/configs/clientSecrets.json").file

GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream(clientSecretsFile)))

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport()

FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home"), ".store/oauth2_sample"))

List<String> SCOPES = ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"]

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, SCOPES).setDataStoreFactory(dataStoreFactory).build()

Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user")

谢谢。

好吧,我找到了解决方案。

当您创建new LocalServerReceiver()使用new LocalServerReceiver.Builder().setPort(9089).build()

在这种情况下,我选择了一些空端口 9089。实际上LocalServerReceiver是一个 http 服务器,它侦听 google 和 google 将code参数发送到该服务器。 现在您要做的就是在重定向的 URI 中创建一个新条目,在本例中如下所示: http://localhost:9089/Callback 请注意,端口号与我在使用LocalServerReceiver.Builder()类构建服务器时在代码中使用的端口号相同。

瞧!!! 你从谷歌获得了 access_token 和 refresh_token。

快乐的编码...快乐的 Java 客户...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM