【问题标题】:Google Drive API Java, Authentication works for first time onlyGoogle Drive API Java,身份验证仅适用于第一次
【发布时间】:2016-09-14 06:28:05
【问题描述】:

我使用以下代码将文件上传到谷歌驱动器,它用于基于 Java 的 Web 应用程序。除身份验证外,一切正常。

代码的主要问题是它只要求身份验证一次,然后当我运行项目时,它从不要求身份验证。

我希望对客户端发出的每个请求进行身份验证。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package myapp.util;

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.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.*;
import com.google.api.services.drive.Drive;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

public class GDrive {

    /**
     * Application name.
     */
    private static final String APPLICATION_NAME
            = "Drive API Java Quickstart";

    /**
     * Directory to store user credentials for this application.
     */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/drive-java-quickstart.json");

    /**
     * Global instance of the {@link FileDataStoreFactory}.
     */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /**
     * Global instance of the JSON factory.
     */
    private static final JsonFactory JSON_FACTORY
            = JacksonFactory.getDefaultInstance();

    /**
     * Global instance of the HTTP transport.
     */
    private static HttpTransport HTTP_TRANSPORT;

    /**
     * Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials at
     * ~/.credentials/drive-java-quickstart
     */
    private static final List<String> SCOPES
            = Arrays.asList(DriveScopes.DRIVE_FILE);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Creates an authorized Credential object.
     *
     * @return an authorized Credential object.
     * @throws IOException
     */
    public static Credential authorize() throws IOException {
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        String basePath = servletContext.getRealPath("");
        basePath = URLDecoder.decode(basePath, "UTF-8");
        // Load client secrets.
        InputStream in = new FileInputStream(
                new java.io.File(basePath + "/resources/client_secret.json"));
        GoogleClientSecrets clientSecrets
                = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow
                = new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(DATA_STORE_FACTORY)
                .setAccessType("offline")
                .setApprovalPrompt("auto")
                .build();

       GoogleCredential credential  = new GoogleCredential();
        System.out.println(
                "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }

    /**
     * Build and return an authorized Drive client service.
     *
     * @return an authorized Drive client service
     * @throws IOException
     */
    public static Drive getDriveService() throws IOException {
        Credential credential = authorize();
        System.out.println("getAccessToken" + credential.getAccessToken());

        System.out.println("setAccessToken" + credential.getAccessToken());
        System.out.println("setExpiresInSeconds" + credential.getExpiresInSeconds());

        System.out.println("setRefreshToken" + credential.getRefreshToken());
        return new Drive.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    public boolean uploadToDrive(String filePathUrl, String fileName) throws FileNotFoundException, IOException, GeneralSecurityException, Exception {
        Drive service = GDrive.getDriveService();
        boolean status = false;
        // TODO code application logic here
        java.io.File mediaFile = new java.io.File(filePathUrl);
        com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
        fileMetadata.setName(fileName);
        InputStreamContent mediaContent = new InputStreamContent("application/octet-stream", new BufferedInputStream(new FileInputStream(mediaFile)));
        mediaContent.setLength(mediaFile.length());

        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

        Drive.Files.Create request = service.files().create(fileMetadata, mediaContent);
        request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
        request.execute();
        status = true;
        return status;
    }

}

class CustomProgressListener implements MediaHttpUploaderProgressListener {

    public void progressChanged(MediaHttpUploader uploader) throws IOException {
        switch (uploader.getUploadState()) {
            case INITIATION_STARTED:
                System.out.println("Initiation has started!");
                break;
            case INITIATION_COMPLETE:
                System.out.println("Initiation is complete!");
                break;
            case MEDIA_IN_PROGRESS:
                System.out.println(uploader.getProgress());
                break;
            case MEDIA_COMPLETE:
                System.out.println("Upload is complete!");
        }
    }
}

【问题讨论】:

  • 在 setDataStoreFactory(DATA_STORE_FACTORY) 中进行过。我的猜测是控制它。
  • 你可以在代码中看到,我已经为 GoogleAuthorizationCodeFlow 设置了数据存储工厂
  • FileDataStoreFactory 可能正在某个地方保存身份验证。一旦您进行了身份验证,一旦它可能保存在您的硬盘上。您需要弄清楚如何告诉它它是不同的用户或使用不同的数据存储。 developers.google.com/api-client-library/java/…
  • 好的,谢谢先生。你对这些有什么想法吗?
  • 是的,我的想法就是我刚刚给你的要点。要么告诉 filedatastore 它的用户不同,要么更改为另一种类型的数据存储。

标签: java google-api google-drive-api google-api-java-client google-oauth


【解决方案1】:

根据设计,客户端库存储授权信息,因此用户不会在每次运行您的应用程序时都收到提示。客户端库将授权信息保存到您提供的DataStore 实例中,在您的情况下为FileDataStore,它将文件存储在特定目录中。

多个用户可以共享同一个数据存储,但在执行授权时需要传递唯一的用户标识符。对于已安装的应用程序,这是在 AuthorizationCodeInstalledApp.authorize 中完成的,对于 Web 应用程序,它是通过覆盖 AbstractAuthorizationCodeServlet.getUserIdAbstractAuthorizationCodeCallbackServlet.getUserId 来完成的。有关更多信息和示例,请参阅 Java 客户端库的 OAuth2 guide

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多