#javascript #sql-server #jsp #jakarta-ee #oauth-2.0
#javascript #sql-сервер #jsp #джакарта-ee #oauth-2.0
Вопрос:
Я пытаюсь решить проблему, которая у меня есть с моими веб-сервисами. Я прочитал весь документ о outh2.0 на Java и интегрировал электронную таблицу, и у меня возникли 3 проблемы.
Мое веб-приложение, которое я использую, содержит файлы jsp и Servlet. У меня есть форма, в которой пользователь заполняет поля, а затем нажимает кнопку отправки. Затем запускается токен потока. Если сначала на странице предлагается указать адрес электронной почты, то, если пользователь Примет или запретит доступ, кроме них…Я не умею ничего контролировать.
1.- Страница «обратный вызов», сколько методов мне нужно? какой тип нужен странице: JSP или html o Servlet? Я не знаю. Я знаю, что в моей консоли api я настраиваю (идентификатор клиента, секрет клиента, я могу загрузить файл json, Авторизованные источники JavaScript, Авторизованные URI перенаправления), но я не знаю в своем коде, где это можно увидеть. У меня есть в Java это:
общедоступный класс 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, %sn", row.get(0), row.get(1), row.get(2));
}
}
}
}
У меня есть мой файл json, и все в порядке. Я не вижу, где мне нужно увидеть access_toke или как я могу его получить.
У кого-нибудь есть какой-нибудь пример с этим или может мне помочь, пожалуйста?
Спасибо!!!!
Ответ №1:
Решена. Здесь помещен мой код.
общедоступный класс 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("amp;response_type=code")
.append("amp;scope=").append(SCOPE) //scope is the api permissions we are requesting
.append("amp;redirect_uri=").append(redirectUrl) //the servlet that google redirects to after authorization
.append("amp;state=").append(request.getSession().getId())//ID de la sesion del usuario
.append("amp;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;
}