Acceso S3 con prefirma
This commit is contained in:
parent
9f1c623f7d
commit
16b178b2e1
Binary file not shown.
|
Before Width: | Height: | Size: 156 KiB After Width: | Height: | Size: 216 KiB |
@ -1,4 +1,4 @@
|
||||
package org.lapaloma.pfc.gestores;
|
||||
package org.lapaloma.pfc.back;
|
||||
|
||||
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
@ -1,40 +1,21 @@
|
||||
package org.lapaloma.pfc;
|
||||
package org.lapaloma.pfc.back;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URL;
|
||||
import java.time.Duration;
|
||||
|
||||
import org.lapaloma.pfc.gestores.GestorClientesServiciosAWS;
|
||||
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;
|
||||
|
||||
public class AppPrincipal {
|
||||
public class GestorObjetosS3 {
|
||||
private final static String NOMBRE_BUCKET_EN_S3 = "s3-obj-proyecto1";
|
||||
|
||||
private static final int TIEMPO_VIDA_MINUTOS_URL = 10;
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
AppPrincipal app = new AppPrincipal();
|
||||
|
||||
// Información del bucket y del archivo a subir
|
||||
int idProyecto = 1;
|
||||
int numeroHito = 2;
|
||||
File documentoEjemplo = new File("fichero/subida_archivos_a_s3.jpg");
|
||||
String claveDocumento = idProyecto + "/" + numeroHito + "/" + documentoEjemplo.getName();
|
||||
|
||||
String urlDocumentoAlmacenado = app.almacenarDocumentoEnS3(claveDocumento, documentoEjemplo);
|
||||
System.out.println("URL del objeto en S3 para hacer un 'PUT': " + urlDocumentoAlmacenado);
|
||||
|
||||
String urlDocumentoConsultado = app.consultarDocumentoEnS3(claveDocumento);
|
||||
System.out.println("URL del objeto en S3 para hacer un 'GET': " + urlDocumentoConsultado);
|
||||
}
|
||||
|
||||
private String almacenarDocumentoEnS3(String clave, File documento) {
|
||||
public String obtenerURLPutDocumentoEnS3(String clave, File documento) {
|
||||
String urlObjetoS3 = null;
|
||||
|
||||
// Solicitud para subir el archivo (método PUT)
|
||||
@ -45,9 +26,8 @@ public class AppPrincipal {
|
||||
|
||||
// Generar la URL firmada
|
||||
PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
|
||||
.signatureDuration(Duration.ofMinutes(TIEMPO_VIDA_MINUTOS_URL)) // Tiempo expiración URL firmada
|
||||
.putObjectRequest(putObjectRequest)
|
||||
.build();
|
||||
.signatureDuration(Duration.ofMinutes(TIEMPO_VIDA_MINUTOS_URL)) // Tiempo expiración URL firmada
|
||||
.putObjectRequest(putObjectRequest).build();
|
||||
|
||||
// Obtener la URL firmada
|
||||
URL presignedUrl = presigner.presignPutObject(presignRequest).url();
|
||||
@ -59,7 +39,7 @@ public class AppPrincipal {
|
||||
return urlObjetoS3;
|
||||
}
|
||||
|
||||
private String consultarDocumentoEnS3(String claveDocumento) {
|
||||
public String obtenerURLGetDocumentoEnS3(String claveDocumento) {
|
||||
String urlObjetoS3 = null;
|
||||
|
||||
// Crear la solicitud de obtención de objeto (método GET)
|
||||
@ -71,7 +51,10 @@ public class AppPrincipal {
|
||||
|
||||
// Generar la URL firmada
|
||||
PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(builder -> builder
|
||||
.getObjectRequest(getObjectRequest).signatureDuration(Duration.ofMinutes(TIEMPO_VIDA_MINUTOS_URL)) // Tiempo expiración URL firmada
|
||||
.getObjectRequest(getObjectRequest).signatureDuration(Duration.ofMinutes(TIEMPO_VIDA_MINUTOS_URL)) // Tiempo
|
||||
// expiración
|
||||
// URL
|
||||
// firmada
|
||||
);
|
||||
|
||||
// Obtener la URL firmada
|
||||
@ -80,8 +63,7 @@ public class AppPrincipal {
|
||||
|
||||
// Cerrar el presigner
|
||||
presigner.close();
|
||||
|
||||
|
||||
return urlObjetoS3;
|
||||
}
|
||||
|
||||
}
|
||||
104
src/main/java/org/lapaloma/pfc/front/AppPrincipal.java
Normal file
104
src/main/java/org/lapaloma/pfc/front/AppPrincipal.java
Normal file
@ -0,0 +1,104 @@
|
||||
package org.lapaloma.pfc.front;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.lapaloma.pfc.back.GestorObjetosS3;
|
||||
|
||||
public class AppPrincipal {
|
||||
public static void main(String[] args) {
|
||||
AppPrincipal appPrincipal = new AppPrincipal();
|
||||
// Información del archivo a subir
|
||||
int idProyecto = 1;
|
||||
int numeroHito = 2;
|
||||
|
||||
File documentoEjemplo = new File("fichero/subida_archivos_a_s3.jpg");
|
||||
String claveDocumento = idProyecto + "/" + numeroHito + "/" + documentoEjemplo.getName();
|
||||
String contentType = "image/jpeg";
|
||||
|
||||
appPrincipal.almacenarDocumentoEnS3DesdeCliente(claveDocumento, documentoEjemplo, contentType);
|
||||
|
||||
|
||||
String urlDocumentoConsultadoPrefirmado = appPrincipal.consultarDocumentoEnS3EnCliente(claveDocumento);
|
||||
System.out.println("URL del objeto en S3 para hacer un 'GET': " + urlDocumentoConsultadoPrefirmado);
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void almacenarDocumentoEnS3DesdeCliente(String claveDocumento, File documentoEjemplo, String contentType) {
|
||||
GestorObjetosS3 gestorObjetosS3 = new GestorObjetosS3();
|
||||
|
||||
// Simulación de la subida del documento a S3 utilizando la URL prefirmada (método PUT)
|
||||
String urlPrefirmadaDocumentoParaAlmacenar = gestorObjetosS3.obtenerURLPutDocumentoEnS3(claveDocumento, documentoEjemplo);
|
||||
|
||||
System.out.println("URL del objeto en S3 para hacer un 'PUT': " + urlPrefirmadaDocumentoParaAlmacenar);
|
||||
|
||||
// 1. Abrir conexión HTTP hacia la URL prefirmada
|
||||
URL url;
|
||||
try {
|
||||
url = new URI(urlPrefirmadaDocumentoParaAlmacenar).toURL();
|
||||
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
|
||||
// 2. Configurar método PUT
|
||||
connection.setRequestMethod("PUT");
|
||||
connection.setDoOutput(true);
|
||||
|
||||
// 3. IMPORTANTE: si la URL se firmó con Content-Type, debe coincidir
|
||||
if (contentType != null) {
|
||||
connection.setRequestProperty("Content-Type", contentType);
|
||||
}
|
||||
|
||||
// 4. (Opcional) desactivar cache HTTP del cliente
|
||||
connection.setUseCaches(false);
|
||||
|
||||
// 5. Escribir el fichero en el body del request
|
||||
try (FileInputStream fis = new FileInputStream(documentoEjemplo);
|
||||
OutputStream os = connection.getOutputStream()) {
|
||||
|
||||
byte[] buffer = new byte[8192];
|
||||
int bytesRead;
|
||||
|
||||
while ((bytesRead = fis.read(buffer)) != -1) {
|
||||
os.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Ejecutar petición y leer respuesta
|
||||
int responseCode = connection.getResponseCode();
|
||||
|
||||
System.out.println("HTTP Response Code: " + responseCode);
|
||||
|
||||
if (responseCode >= 200 && responseCode < 300) {
|
||||
System.out.println("✔ Upload correcto a S3");
|
||||
} else {
|
||||
System.out.println("❌ Error al subir archivo");
|
||||
}
|
||||
|
||||
connection.disconnect();
|
||||
|
||||
} catch (IOException | URISyntaxException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private String consultarDocumentoEnS3EnCliente(String claveDocumento) {
|
||||
String urlDocumentoConsultado = null;
|
||||
GestorObjetosS3 gestorObjetosS3 = new GestorObjetosS3();
|
||||
|
||||
// Simulación de la consulta del documento en S3 utilizando la URL prefirmada (método GET)
|
||||
urlDocumentoConsultado = gestorObjetosS3.obtenerURLGetDocumentoEnS3(claveDocumento);
|
||||
|
||||
return urlDocumentoConsultado;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user