在服务器端验证Google Drive API,而不提示用户登录

时间:2013-09-04 08:24:37

标签: java google-drive-api

所以情况就是这样。我正在设计一个网站,人们可以在其中创建他们的个人资料。创建的个人资料图像上传到我的谷歌硬盘中,然后使用Google Drive API共享。我正在尝试使用oAuth 2.0身份验证进行身份验证。但每次都会提示登录用户(客户端)并将配置文件图像上传到他们的谷歌硬盘中。我只需要一次,或者说是开放式身份验证,这样用户就可以直接在我的驱动器中上传他们的照片..

我在服务器端的代码是这样的......

package com.gamesquad.uploads;

..//imports done;

public class GoogleDriveServices {
private static Logger log = Logger.getLogger(GoogleDriveServices.class);
static HttpTransport httpTransport = new NetHttpTransport();
    static JsonFactory jsonFactory = new JacksonFactory();
static Properties connectionprop = new Properties();
private static GoogleAuthorizationCodeFlow flow=null;

public static void initiParameteres(){
    try {
           connectionprop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("connection.properties"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

//1.get the authorization url 
public static String authorize(){
    flow= new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,connectionprop.getProperty("googleappclientid"),connectionprop.getProperty("googleappclientsecret"),Arrays.asList(DriveScopes.DRIVE)).setAccessType("online").setApprovalPrompt("auto").build();
    String url = flow.newAuthorizationUrl().setRedirectUri(connectionprop.getProperty("googleappredirecturi")).build();
    return url;
}
//2.get authenticated client
public static Drive createAuthorizedClient(String code) throws IOException{
    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(connectionprop.getProperty("googleappredirecturi")).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
    return service;
}
//3.upload a file
public static String uploadNewFileinGoogleDrive(java.io.File inputfile,Drive service) throws IOException,MalformedURLException {
    //Insert a file  
    String mimeType="image/"+inputfile.getName().substring(inputfile.getName().lastIndexOf(".") + 1, inputfile.getName().length());
    File body = new File();
    body.setTitle("Profilepic_"+System.currentTimeMillis());
    body.setDescription("Profile Picture");
    body.setMimeType(mimeType);
    body.setShared(true);
    java.io.File fileContent = new java.io.File(inputfile.getAbsolutePath());
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    File file = service.files().insert(body, mediaContent).execute();
    //file uploaded
    //share the file
    Permission permission = new Permission();
    permission.setValue("");
    permission.setType("anyone");
    permission.setRole("reader");
    Property newProperty = new Property();
    newProperty.setVisibility("PUBLIC");
    try {
        service.permissions().insert(file.getId(), permission).execute();
        service.properties().insert(file.getId(), newProperty).execute();
    } catch (Exception e) {
         log.error("An error occurred: " + e);
    }
    //file shared
    log.info("File ID: " + file.getId());
    return file.getId();
  }
}

2 个答案:

答案 0 :(得分:3)

您需要使用服务帐户。请参阅https://developers.google.com/accounts/docs/OAuth2ServiceAccount

从该页面上可以看出“请求的应用程序必须证明自己的身份才能访问API,最终用户无需参与。”

答案 1 :(得分:1)

在检索访问令牌(以及可选的刷新令牌)后,不再使用GoogleAuthorizationCodeFlow,而是永久保留它并使用保留的访问令牌填充Drive服务:

GoogleCredential credential = new GoogleCredential();
credential.setAccessToken(accessToken);
credential.setRefreshToken(refreshToken);

protected Drive getDriveService(Credential credential) {
    return new Drive.Builder(TRANSPORT, JSON_FACTORY, credential).build();
}