【问题标题】:Where are OAuth 2.0 with Gmail for Server-Side Authorization examples for Java?带有 Gmail 的 OAuth 2.0 用于 Java 的服务器端授权示例在哪里?
【发布时间】:2018-01-22 12:48:34
【问题描述】:

我需要为用 Java 编写的 Web 应用程序实现 OAuth2 以访问 Gmail。不幸的是,谷歌的文档只有一个关于这个主题的 Python 示例: https://developers.google.com/gmail/api/auth/web-server

我已经用谷歌搜索了几个小时,但找不到一个很好的例子来解释这个主题 - 我是 OAuth2 的新手,因此 Java 中的分步示例会非常有用。

提前致谢:)

【问题讨论】:

  • @VladBochenin 感谢您的评论。是的,我已经看到了,但是这个例子的问题是,“public static Credential authorize()”只打印到命令行,而不是返回 url 来重定向用户。我不知道,但据我所知,我不能将代码用于 Web 应用程序..

标签: java oauth-2.0


【解决方案1】:

我已尝试为 Gmail 快速入门指南做出贡献。我认为阻力最小的路径是复制我这里的内容。

假设你有你的秘密,并且你已经在之前的授权过程中获得了一个 refresh_token。你可以试试这个。


    /**
     * Assuming the user of this application has already obtained an refresh_token, this will create a Credential object
     * using the provided secrets and the provided refresh_token.
     *
     * @param refreshToken   Refresh Token obtained in previous authorization process
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final String refreshToken, final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        GoogleClientSecrets clientSecrets = getGoogleClientSecrets();

        return new GoogleCredential.Builder()
                .setJsonFactory(JSON_FACTORY)
                .setTransport(HTTP_TRANSPORT)
                .setClientSecrets(clientSecrets)
                .build().setRefreshToken(refreshToken);
    }

完整版:GmailQuickstart.java

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START gmail_quickstart]
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;

import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class GmailQuickstart {
    private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
    private static final String CREDENTIALS_FILE_PATH = "credentials.json";

    private static GoogleClientSecrets getGoogleClientSecrets() throws IOException {
        // Load client secrets.
        File credentialJson = new File(CREDENTIALS_FILE_PATH);
        if (!credentialJson.exists()) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialJson)));
    }
    /**
     * Launches a small local server on 8888 which facilitates the authorization process from scratch.  In turn creates
     * an authorized Credential object when the user proceeds with the authorization.
     *
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        GoogleClientSecrets clientSecrets = getGoogleClientSecrets();

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    /**
     * Assuming the user of this application already has an refresh_token handy, this will create a Credential object
     * using the provided secrets and the provided refresh_token.
     *
     * @param refreshToken   Refresh Token obtained in previous authorization process
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final String refreshToken, final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        GoogleClientSecrets clientSecrets = getGoogleClientSecrets();

        return new GoogleCredential.Builder()
                .setJsonFactory(JSON_FACTORY)
                .setTransport(HTTP_TRANSPORT)
                .setClientSecrets(clientSecrets)
                .build().setRefreshToken(refreshToken);
    }


    private static Credential getCredential(NetHttpTransport HTTP_TRANSPORT) throws IOException {
        Credential credentials;
        switch (getAuthPreference()) {
            case FULL_AUTH:
                credentials = getCredentials(HTTP_TRANSPORT);
                break;
            case REFRESH_AUTH:
                System.out.print("please provide refresh_token:");
                String refreshToken = getUserInput();
                credentials = getCredentials(refreshToken, HTTP_TRANSPORT);
                break;
            default:
                credentials = getCredentials(HTTP_TRANSPORT);
        }
        return credentials;
    }

    private static WhatToDo getAuthPreference() throws IOException {
        // Enter data using BufferReader
        System.out.println("You can choose how to authorize your request.");
        System.out.println("\t1) Need to do full authorization");
        System.out.println("\t2) Already have refresh_token handy.  Can provide this next.");
        String userInput = getUserInput();
        if (userInput.equals("1")) {
            return WhatToDo.FULL_AUTH;
        }
        if (userInput.equals("2")) {
            return WhatToDo.REFRESH_AUTH;
        }
        System.err.println("Your Input was incorrect! ");
        return getAuthPreference();
    }

    private static String getUserInput() throws IOException {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(System.in));
        // Reading data using readLine
        String userInput = reader.readLine();
        return userInput;
    }

    enum WhatToDo {
        FULL_AUTH,
        REFRESH_AUTH
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredential(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Print the labels in the user's account.
        String user = "me";
        ListLabelsResponse listResponse = service.users().labels().list(user).execute();
        List<Label> labels = listResponse.getLabels();
        if (labels.isEmpty()) {
            System.out.println("No labels found.");
        } else {
            System.out.println("Labels:");
            for (Label label : labels) {
                System.out.printf("- %s\n", label.getName());
            }
        }
    }
}
// [END gmail_quickstart]

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 2013-10-05
    • 2015-01-15
    • 1970-01-01
    • 2015-05-14
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多