【发布时间】:2021-08-19 12:49:33
【问题描述】:
我已经阅读了很多帖子,我能找到的所有 Google 文档,并尝试了以下多次迭代,但仍然无法获得访问和刷新令牌。我确实得到了一个授权码,但似乎无法用它来换取访问和刷新令牌。
if(authCode == null || authCode.equals("")) {
String url = "https://accounts.google.com/o/oauth2/v2/auth?"
+ "scope=https://mail.google.com/&"
+ "response_type=code&"
+ "redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&"
+ "client_id=" + clientId +
"&access_type=offline";
URI uri = new URI(url);
logger.debug("URI for auth is: " + uri);
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
}
}
else {
logger.debug("Refreshing");
initRefreshToken();
}
这样,我得到一个访问代码,我可以在我的属性中剪切和粘贴(只是测试并尝试使其首先工作)以获取刷新和访问令牌。
在initRefreshToken()方法中,源码是这样的:
if(refreshToken.equals("")) {
logger.debug("Getting refresh token");
HttpPost post = new HttpPost("https://oauth2.googleapis.com/token");
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("code", authCode));
urlParameters.add(new BasicNameValuePair("client_id", clientId));
urlParameters.add(new BasicNameValuePair("client_secret", clientSecret));
urlParameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8000/"));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
System.out.println("***** URL: " + urlParameters);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
}
如果这是第二次或以后使用该代码,将打印的内容是:
刷新令牌: ***** URL:[code=4/1AY0e-g...,client_id=370...i1h2u1s.apps.googleusercontent.com,client_secret=bAOH...,redirect_uri=https://localhost:8000/ , grant_type=authorization_code]
{ “错误”:“invalid_grant”, "error_description": "错误请求" }
如果代码运行并且是第一次使用验证码,它将打印:
{ “错误”:“redirect_uri_mismatch”, "error_description": "错误请求" }
我在 Google 控制台中读到,本地主机域存在例外情况,因此无需注册它们。但是,如果需要注册它们,无论如何它都不会让您注册它们,因为域必须是您拥有的顶级域才能注册。因此,如何在 Java 中注册 localhost 和/或交换授权码以获取访问和刷新令牌?
感谢您的帮助。
【问题讨论】:
-
你为什么要手动为什么不使用客户端库?
-
我有一个视频,它解释了使用 curl 的每个步骤,它可能会有所帮助 youtu.be/hBC_tVJIx5w 我认为您的授权类型是错误的。
-
您的代码不完整,请提供minimal steps to reproduce您的问题。谢谢
-
我手动执行此操作是因为我想理解并且因为我没有理由不能发送帖子并获得响应,这可能是任何库的底层代码无论如何都会做的事情。我的授权类型是正确的,但你帮我修复了 URI。我的代码已完成...感谢您的回复。
标签: authentication oauth-2.0 oauth google-oauth gmail-api