2016-10-20 7 views
0

웹 서비스 관련 문제를 해결하려고합니다. Java에서 outh2.0에 대한 모든 문서를 읽었으며 스프레드 시트를 통합하기 위해 3 가지 문제점이 있습니다.스프레드 시트 v4를 사용하는 오류 콜백 OAuth2.0

내가 사용하는 웹 응용 프로그램에 jsp 및 Servlet 파일이 있습니다. 사용자가 입력란을 채운 다음 제출 버튼을 클릭하는 양식이 있습니다. 그런 다음 플로우 토큰을 시작합니다. 전자 메일을 넣으려면 먼저 페이지 호출을하고, 그 다음에 사용자가 액세스를 수락하거나 해지한다면 controle을 모르십시오.

1. 페이지 "콜백", 몇 가지 방법이 필요합니까? 어떤 종류의 페이지가 필요 : JSP 또는 HTML 서블릿? 나는 모른다. 내 API 콘솔에서 클라이언트 ID, 클라이언트 비밀 번호, 파일 json, 허가 된 JavaScript 원본, 허가 된 리디렉션 URI를 다운로드 할 수 있음을 알고 있지만 어디에서 볼 수 있는지는 내 코드에서 알 수 없습니다.

공용 클래스 SheetsQuickstart {

/** Application name. */ 
private static final String APPLICATION_NAME = "Name_APP"; 

/** 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/sheets.googleapis.com-java-quickstart"); 

/** 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/sheets.googleapis.com-java-quickstart 
*/ 
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS_READONLY); 

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 { 

    /** Load client secrets. 
    * */ 
    InputStream in = new FileInputStream("\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") 
      .build(); 

    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); 

    Credential credential = new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); 

    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); 

    return credential; 
} 

/** 
* Build and return an authorized Sheets API client service. 
* @return an authorized Sheets API client service 
* @throws IOException 
*/ 
public static Sheets getSheetsService() throws IOException { 

    Credential credential = authorize(); 
    return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
      .setApplicationName(APPLICATION_NAME) 
      .build();    
} 

public static void main(String[] args) throws IOException { 

    // Build a new authorized API client service. 
    Sheets service = getSheetsService(); 

    // Prints the names and majors of students in a sample spreadsheet: 
    String spreadsheetId = "Id spreadsheet"; 
    String range = "A4:C6"; 
    ValueRange response = service.spreadsheets().values() 
     .get(spreadsheetId, range) 
     .execute(); 
    List<List<Object>> values = response.getValues(); 
    if (values == null || values.size() == 0) { 
     System.out.println("No data found."); 
    } else { 
     System.out.println("Name, Major"); 
     for (List<?> row : values) { 
     // Print columns A and E, which correspond to indices 0 and 4. 
     System.out.printf("%s, %s\n", row.get(0), row.get(1), row.get(2)); 
     } 
    } 
} 

}

내 파일 JSON을하고 OK입니다 : 나는 자바이에 있습니다. access_toke를 어디에서 볼 수 있는지 또는 어떻게 얻을 수 있는지 알 수 없습니다.

누군가가이 예제를 사용하고 있습니까, 아니면 저를 도울 수 있습니까?

감사합니다 !!!!

답변

0

해결되었습니다. 여기에 내 코드를 넣어.

공용 클래스 ServletOAuth2Callback은 HttpServlet을 확장 {

private static final long serialVersionUID = 1L; 

public static String GOOGLE_CLIENT_ID = ""; 
public static String GOOGLE_CLIENT_SECRET = ""; 


public ServletOAuth2Callback() { 
    super(); 
} 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 


    String stateP = request.getParameter("state"); 
    System.out.println("stateP --> " +stateP); 


    /** No funciona */ 
    String error = request.getParameter("error"); 


    if(error != null){ 

     System.out.println(""); 
     String volverAJsp = ""; 
     response.sendRedirect(volverAJsp); 
    } 

    else{ 

     System.out.println("El usuario ha aceptado el acceso"); 
     String code = request.getParameter("code"); 
     System.out.println("code --> " +code); 


     GoogleAuthorizationCodeFlow flujo = null; 
     flujo = AutorizacionOAuth2.newFlow(); 
     System.out.println("Flujo string   --> " +flujo.toString()); 
     System.out.println("Flujo token encodeurl --> " +flujo.getTokenServerEncodedUrl()); 
     System.out.println("Flujo access_type  --> " +flujo.getAccessType()); //ahora mismo es null 
     System.out.println("Flujo client_id   --> " +flujo.getClientId()); 
     System.out.println("Flujo scopes as string --> " +flujo.getScopesAsString()); 
     System.out.println("Flujo nuevo token  --> " +flujo.newTokenRequest(code)); 

     GoogleTokenResponse token = null; 
     token = AutorizacionOAuth2.requestAccessToken(flujo, code); 
     //System.out.println("Token toString --> " +token.toString()); 

     System.out.println("Token access  --> " +token.getAccessToken()); 
     System.out.println("Token expire  --> " +token.getExpiresInSeconds()); 
     System.out.println("Token type  --> " +token.getTokenType()); 

     String urlSsSession = (String) request.getSession().getAttribute("URL"); 
     System.out.println("La UrlSsSession --> " +urlSsSession); 

     String idHoja = urlSsSession.substring(39, 83); 
     System.out.println("idHoja --> " +idHoja); 

     Sheets service = AutorizacionOAuth2.getSheetsService(flujo, token); 
     System.out.println("Servicio string --> " +service.toString()); 
     System.out.println("Servicio name --> " +service.getApplicationName()); 
     System.out.println("Servicio sheets --> " +service.spreadsheets().sheets().toString()); 

     String spreadsheetId = idHoja; 
     String range = "A4:C"; 

     System.out.println("Spreadsheet --> " +spreadsheetId.toString()); 
     System.out.println("range  --> " +range); 

     Get respuesta = service.spreadsheets().values() 
       .get(spreadsheetId, range); 

     System.out.println("Get respuesta --> " +respuesta.toString()); 
     System.out.println("Exe respuesta --> " +respuesta.execute());      
    } 
} 

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    System.out.println("----------------------------------------------------------"); 
    System.out.println("Estamos en el metodo doPost() en la clase SOAuth2Callback."); 

    String urlSpreadsheet = request.getParameter("URL"); 
    System.out.println("La URL del text --> " +urlSpreadsheet); 

    request.getSession().setAttribute("URL", urlSpreadsheet); 

    String variable = AutorizacionOAuth2.getOauthUrlGoogle(request, urlSpreadsheet); 
    System.out.println("Metodo getOauthUrlGoogle--> " +variable); 

    String estado = request.getSession().getId(); 
    System.out.println("estado --> " +estado); 

    response.sendRedirect(variable);  
} 

공용 클래스 AutorizacionOAuth2 {

private static String CLIENT_ID = ""; 
private static final String SCOPE = "https://www.googleapis.com/auth/drive"; 

private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE); 

private static final String APPLICATION_NAME = ""; 

private static FileDataStoreFactory DATA_STORE_FACTORY = null; 

private static HttpTransport HTTP_TRANSPORT = null; 

private static JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 

private static String client_id = ""; 
private static String client_secret = ""; 

private static String redirectUrl = ""; 

private static java.io.File DATA_STORE_DIR = new java.io.File(
     System.getProperty("user.home"), "credentials/creden_json/"); 

public static String getCallbackUrl() { 

    System.out.println("Estamos en el metodo getCallbackUrl() en la clase AutorizacionOAuth2."); 

    String redirectUrl = ""; 

    return redirectUrl; 
} 


public static GoogleTokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code) throws IOException, GoogleJsonResponseException { 

    System.out.println("Estamos en el metodo requestAccessToken() en la clase AutorizacionOAuth2."); 

    return (GoogleTokenResponse) flow.newTokenRequest(code).setRedirectUri("http://localhost:8080/appweb/ServletOAuth2Callback").execute(); 
} 

public static String getOauthUrlGoogle(HttpServletRequest request, String urlSpreadsheet) { 

    System.out.println("Estamos en el metodo getOauthUrlGooglePrueba() en la clase AutorizacionOAuth2."); 

    StringBuilder oauthUrl = new StringBuilder(); 
    oauthUrl.append("https://accounts.google.com/o/oauth2/auth") 
     .append("?client_id=").append(CLIENT_ID) //the client id from the api console registration 
     .append("&response_type=code") 
     .append("&scope=").append(SCOPE) //scope is the api permissions we are requesting 
     .append("&redirect_uri=").append(redirectUrl) //the servlet that google redirects to after authorization 
     .append("&state=").append(request.getSession().getId())//ID de la sesion del usuario 
     .append("&urlSpreadsheet=").append(urlSpreadsheet); 

    return oauthUrl.toString(); 
} 

public static GoogleAuthorizationCodeFlow newFlow() throws IOException{ 

    System.out.println("Estamos en el metodo GoogleAuthorizationCodeFlow() en la clase AutorizacionOAuth2."); 

    try { 

     HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 
     DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); 
    } 

    catch (Throwable t) { 

     System.out.println("Ha fallado la ruta de DATA_STORE_DIR"); 
     t.printStackTrace(); 
     //System.exit(1); 
    } 

return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, 
     client_id, client_secret, SCOPES) 
      .setDataStoreFactory(DATA_STORE_FACTORY) 
      .setApprovalPrompt("force") 
      .setAccessType("offline") 
      .build(); 
} 


public static Sheets getSheetsService(GoogleAuthorizationCodeFlow flujo, GoogleTokenResponse token) throws IOException { 

    System.out.println("Estamos en el metodo getSheetsService() en la clase AutorizacionOAuth2."); 

    try{ 

     GoogleCredential credential = AutorizacionOAuth2.autorizar(flujo); 

     credential.setFromTokenResponse(token); 
     credential.refreshToken(); 

     System.out.println("Ya tenemos la credenciales en la variable credential."); 

     return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
       .setApplicationName(APPLICATION_NAME) 
       .build();  
    } 
    catch(IOException io){ 
     System.out.println("Estamos en la excepcion"); 
     io.getMessage(); 
     return null; 
    } 
} 


public static GoogleCredential autorizar(GoogleAuthorizationCodeFlow flujo) throws IOException { 

    System.out.println("Estamos en el metodo autorizar() en la clase AutorizacionOAuth2."); 

    InputStream clientSecretReader = new FileInputStream(""); 
    GoogleClientSecrets clientSecrets = GoogleClientSecrets 
      .load(JSON_FACTORY, new InputStreamReader(clientSecretReader)); 

    GoogleCredential credential = new GoogleCredential.Builder() 
      .setTransport(HTTP_TRANSPORT) 
      .setJsonFactory(JSON_FACTORY) 
      .setClientSecrets(clientSecrets) 
      .build(); 

    System.out.println("Credentials guardadas en " + DATA_STORE_DIR.getAbsolutePath()); 
    System.out.println("Credenciales --> " +credential.toString()); 

    return credential; 
} 
관련 문제