使用 Java 中发布的授权令牌从 Google 获取刷新令牌

时间:2021-06-01 10:08:18

标签: authentication oauth-2.0 oauth google-oauth gmail-api

我已经阅读了很多帖子,我可以找到的所有 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 和/或交换授权码以获取访问和刷新令牌?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

DaImTo 提供了一个关于此的精彩视频,在该视频和与之相关的博客文章中,redirect_uri 正确列出为:“urn:ietf:wg:oauth:2.0:oob”。我没有在文档中找到这个,但是当我将它添加到我的源代码时,我得到了访问和刷新令牌作为响应。非常感谢您的帮助,DaImTo。