所以情况就是这样。我正在设计一个网站,人们可以在其中创建他们的个人资料。创建的个人资料图片上传到我的谷歌驱动器中,然后使用谷歌驱动器 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();
}
}