简体   繁体   English

使用OAuth 2.0进行Java和Google Spreadsheets API授权

[英]Java and Google Spreadsheets API Authorization with OAuth 2.0

I want to read Google Spreadsheets using Java, and the recommended way to do this is using the Google Spreadsheets API . 我想使用Java阅读Google Spreadsheets,推荐的方法是使用Google Spreadsheets API

The problem begins when you want to make procedures secure, so they encourage you to use OAuth 2.0. 当您想要使程序安全时,问题就开始了,因此他们鼓励您使用OAuth 2.0。 In the official page they show how to do this using only .NET and say that " the Java client library doesn't currently support OAuth 2.0 ", and they give alternatives like using OAuth 1.0 or Client Login using directly email and password . 官方页面中,他们展示了如何仅使用.NET执行此操作,并说“ Java客户端库当前不支持OAuth 2.0 ”,并且他们提供了使用OAuth 1.0或使用直接电子邮件密码进行 Client Login等替代方案。

Is this for sure?, isn't there a way to do OAuth 2.0 Authentication through Java, maybe not using directly the Java client library, but through requests with specific parameters. 这是肯定的吗?,没有办法通过Java进行OAuth 2.0身份验证,也许不是直接使用Java客户端库,而是通过具有特定参数的请求。

Please I would appreciate any suggestions. 请相信任何建议。

I also found it quite silly that the developer docs provided Java examples for everything except OAuth2. 我还发现, 开发人员文档为除OAuth2之外的所有内容提供了Java示例,这非常愚蠢。 Here's some sample code that I used to get it working. 这是我用来使它工作的一些示例代码。 For completeness it includes the retrieving spreadsheets example in the later section. 为了完整起见,它包括后面部分中的检索电子表格示例 Note also that you have to add the required scopes to the Java DrEdit example as shown below. 另请注意,您必须将所需范围添加到Java DrEdit示例,如下所示。

public class GSpreadsheets {

    private static final String CLIENT_ID = "YOUR_CLIENT_ID";
    private static final String CLIENT_SECRET = "YOUR_SECRET_ID";
    private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

    public static void main(String[] args) throws Exception {

        if (CLIENT_ID.equals("YOUR_CLIENT_ID") || CLIENT_SECRET.equals("YOUR_SECRET_ID")) {
            throw new RuntimeException(
                    "TODO: Get client ID and SECRET from https://cloud.google.com/console");
        }

            // get credentials similar to Java DrEdit example
            // https://developers.google.com/drive/examples/java
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
                Arrays.asList(DriveScopes.DRIVE, 
                              "https://spreadsheets.google.com/feeds", 
                              "https://docs.google.com/feeds"))
                .setAccessType("online")
                .setApprovalPrompt("auto").build();

        String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
        System.out.println("Please open the following URL in your "
                + "browser then type the authorization code:");
        System.out.println("  " + url);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String code = br.readLine();

        GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

            // create the service and pass it the credentials you created earlier
        SpreadsheetService service = new SpreadsheetService("MyAppNameHere");
        service.setOAuth2Credentials(credential);

        // Define the URL to request.  This should never change.
        URL SPREADSHEET_FEED_URL = new URL(
            "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

        // Make a request to the API and get all spreadsheets.
        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
        List<SpreadsheetEntry> spreadsheets = feed.getEntries();

        // Iterate through all of the spreadsheets returned
        for (SpreadsheetEntry spreadsheet : spreadsheets) {
          // Print the title of this spreadsheet to the screen
          System.out.println(spreadsheet.getTitle().getPlainText());
        }
    }
}

The Google Data Java Client Library now supports OAuth 2.0: Google Data Java Client Library现在支持OAuth 2.0:

https://code.google.com/p/gdata-java-client/source/detail?r=505 https://code.google.com/p/gdata-java-client/source/detail?r=505

Unfortunately, there are no complete samples in the library showing how to use it. 不幸的是,库中没有完整的样本显示如何使用它。 I'd recommend checking these two links to put together the information to make it work: 我建议检查这两个链接,将信息放在一起使其工作:

[Edit] [编辑]

Java OAuth2 code Java OAuth2代码

Blog post on [google-spreadsheet-api] and OAuth2, with code 博客帖子在[google-spreadsheet-api]和OAuth2上,带有代码
http://soatutorials.blogspot.co.at/2013/08/google-spreadsheet-api-connecting-with.html http://soatutorials.blogspot.co.at/2013/08/google-spreadsheet-api-connecting-with.html

Related question: OAuth2 authorization from Java/Scala using google gdata client API 相关问题: 使用google gdata客户端API从Java / Scala获得OAuth2授权

[end edit] [结束编辑]

I used: Google drive DrEdit tutorial, full example shows how to use OAuth 2.0 with Drive. 我使用过:Google驱动程序DrEdit教程,完整示例演示了如何将OAuth 2.0与Drive配合使用。 The code works with google spreadsheets GData style API. 该代码适用于Google电子表格GData样式API。 (note: does not include refresh token, but the refresh token works as you would expect, so not hard too add.) - (注意:不包括刷新令牌,但刷新令牌的工作方式正如您所期望的那样,所以不要太难添加。) -

Extra Note: A better documented API is Google-Apps-Script. 额外注意:更好的文档API是Google-Apps-Script。

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

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