Авторизация работает локально, но не размещается - PullRequest
0 голосов
/ 27 февраля 2019

Это текущий код, в котором я использую свой файл включения привода "credentials.json" для аутентификации OAuth 2.0 проекта, это нормально работает для локального проекта, перестаньте работать, когда я собираюсь жить этим проектом.

public class GoogleDriveUtils { 

private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";

private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

// Directory to store user credentials for this application.
private static final java.io.File CREDENTIALS_FOLDER //
        = new java.io.File("/tmp/");
private static final String CLIENT_SECRET_FILE_NAME = "credentials.json";

private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);

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

// Global instance of the HTTP transport.
private static HttpTransport HTTP_TRANSPORT;
private static Drive _driveService;
static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(CREDENTIALS_FOLDER);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}
public static Credential getCredentials() throws IOException {
    java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
   if (!clientSecretFilePath.exists()) {
        throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
                + " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
    }
    InputStream in = new FileInputStream(clientSecretFilePath);
    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").build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    return credential;
}

public static Drive getDriveService() throws IOException {
    if (_driveService != null) {
        return _driveService;
    }
    Credential credential = getCredentials();
    //
    _driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
            .setApplicationName(APPLICATION_NAME).build();
    return _driveService;
}

}

1 Ответ

0 голосов
/ 28 февраля 2019

AuthorizationCodeInstalledApp

Используется для Установленных приложений. Это означает, что на компьютере, на котором выполняется код, откроется окно браузера.Если вы размещаете это на веб-сервере, он пытается открыть окно браузера на этом компьютере.Не на машине пользователя.

Вы должны следить за приложениями веб-сервера

public class CalendarServletSample extends AbstractAuthorizationCodeServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    // do stuff
  }

  @Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
    url.setRawPath("/oauth2callback");
    return url.build();
  }

  @Override
  protected AuthorizationCodeFlow initializeFlow() throws IOException {
    return new GoogleAuthorizationCodeFlow.Builder(
        new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
        "[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
        DATA_STORE_FACTORY).setAccessType("offline").build();
  }

  @Override
  protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
    // return user ID
  }
}

public class CalendarServletCallbackSample extends AbstractAuthorizationCodeCallbackServlet {

  @Override
  protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential)
      throws ServletException, IOException {
    resp.sendRedirect("/");
  }

  @Override
  protected void onError(
      HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
      throws ServletException, IOException {
    // handle error
  }

  @Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
    url.setRawPath("/oauth2callback");
    return url.build();
  }

  @Override
  protected AuthorizationCodeFlow initializeFlow() throws IOException {
    return new GoogleAuthorizationCodeFlow.Builder(
        new NetHttpTransport(), JacksonFactory.getDefaultInstance()
        "[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
        DATA_STORE_FACTORY).setAccessType("offline").build();
  }

  @Override
  protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
    // return user ID
  }
}
...