首页 > 解决方案 > 使用发布在 Java 中的授权令牌从 Google 获取刷新令牌

问题描述

我已经阅读了很多帖子,我能找到的所有 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]

{“错误”:“无效授权”,“错误描述”:“错误请求”}

如果代码运行并且它是第一次使用验证码,它将打印:

{“错误”:“redirect_uri_mismatch”,“错误描述”:“错误请求”}

我在 Google 控制台中读到 localhost 域存在例外情况,因此无需注册它们。但是,如果需要注册它们,无论如何它都不会让您注册它们,因为域必须是您拥有的顶级域才能注册。因此,如何在 Java 中注册 localhost 和/或交换授权代码以获取访问和刷新令牌?

谢谢您的帮助。

标签: authenticationoauth-2.0oauthgoogle-oauthgmail-api

解决方案


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


推荐阅读