From d3c19a618645a92d30657cfaa56e6591fe80dd45 Mon Sep 17 00:00:00 2001 From: Jose Date: Sat, 31 Jan 2026 14:25:50 +0100 Subject: [PATCH] Fix: CORS. --- TODO | 2 +- backlib/pom.xml | 2 +- backlib/target/maven-archiver/pom.properties | 2 +- .../compile/default-compile/inputFiles.lst | 3 + core/pom.xml | 2 +- .../backend/core/config/CorsConfig.java | 28 ---- .../backend/core/config/SecurityConfig.java | 23 --- .../core/controller/FileController.java | 37 +++-- huertos/pom.xml | 2 +- .../huertos/client/CoreAuthClient.java | 47 +++++- .../huertos/client/HuertosWebClient.java | 154 ++++++++++++++---- .../backend/huertos/config/CorsConfig.java | 27 --- .../huertos/config/RestTemplateConfig.java | 22 ++- .../huertos/config/SecurityConfig.java | 20 --- 14 files changed, 214 insertions(+), 157 deletions(-) delete mode 100644 core/src/main/java/net/miarma/backend/core/config/CorsConfig.java delete mode 100644 huertos/src/main/java/net/miarma/backend/huertos/config/CorsConfig.java diff --git a/TODO b/TODO index a4ff411..755922e 100644 --- a/TODO +++ b/TODO @@ -1,5 +1,4 @@ POR HACER -------------------------------- -- cambiar contraseña (?) - documentación - mail wrapper @@ -12,3 +11,4 @@ RESUELTO --------------------------------- - implementar urlParams para filtros -> NO RESUELTO (DEPRECATED) - sistema comun de errores en back & front - nombre del requester +- cambiar contraseña (?) diff --git a/backlib/pom.xml b/backlib/pom.xml index a709b92..e13d677 100644 --- a/backlib/pom.xml +++ b/backlib/pom.xml @@ -4,7 +4,7 @@ 4.0.0 backlib net.miarma - 1.0.1 + 1.1.0 25 diff --git a/backlib/target/maven-archiver/pom.properties b/backlib/target/maven-archiver/pom.properties index ea3a998..94832da 100644 --- a/backlib/target/maven-archiver/pom.properties +++ b/backlib/target/maven-archiver/pom.properties @@ -1,3 +1,3 @@ artifactId=backlib groupId=net.miarma -version=1.0.1 +version=1.1.0 diff --git a/backlib/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/backlib/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst index 59236e1..9b45e3d 100644 --- a/backlib/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ b/backlib/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -1,10 +1,12 @@ /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/config/SecurityCommonConfig.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ApiErrorDto.java +/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ApiValidationErrorDto.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangeAvatarRequest.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangePasswordRequest.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangeRoleRequest.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangeStatusRequest.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/CreateCredentialDto.java +/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/CreateUserDto.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/CredentialDto.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/FileDto.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/LoginRequest.java @@ -24,5 +26,6 @@ /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/http/RestAuthEntryPoint.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/CoreAuthTokenHolder.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/JwtService.java +/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/PasswordGenerator.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/ServiceAuthFilter.java /home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/util/UuidUtil.java diff --git a/core/pom.xml b/core/pom.xml index 48b09f8..a68de1a 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -83,7 +83,7 @@ net.miarma backlib - 1.0.1 + 1.1.0 diff --git a/core/src/main/java/net/miarma/backend/core/config/CorsConfig.java b/core/src/main/java/net/miarma/backend/core/config/CorsConfig.java deleted file mode 100644 index ced0782..0000000 --- a/core/src/main/java/net/miarma/backend/core/config/CorsConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.miarma.backend.core.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class CorsConfig { - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins( - "http://localhost:3000", - "http://localhost:8081", - "http://huertos:8081" - ) - .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") - .allowedHeaders("*") - .allowCredentials(true); - } - }; - } -} diff --git a/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java b/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java index 5448bc4..74b7264 100644 --- a/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java +++ b/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java @@ -5,22 +5,13 @@ import net.miarma.backlib.http.RestAccessDeniedHandler; import net.miarma.backlib.http.RestAuthEntryPoint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.Customizer; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; - -import java.util.List; @Configuration @EnableWebSecurity @@ -40,23 +31,9 @@ public class SecurityConfig { this.accessDeniedHandler = accessDeniedHandler; } - @Bean - public CorsConfigurationSource corsConfigurationSource() { - CorsConfiguration config = new CorsConfiguration(); - config.setAllowedOrigins(List.of("http://localhost:3000")); - config.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS")); - config.setAllowedHeaders(List.of("*")); - config.setAllowCredentials(true); - - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", config); - return source; - } - @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http - .cors(Customizer.withDefaults()) .csrf(csrf -> csrf.disable()) .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling(ex -> ex diff --git a/core/src/main/java/net/miarma/backend/core/controller/FileController.java b/core/src/main/java/net/miarma/backend/core/controller/FileController.java index 2fa206d..212a5a0 100644 --- a/core/src/main/java/net/miarma/backend/core/controller/FileController.java +++ b/core/src/main/java/net/miarma/backend/core/controller/FileController.java @@ -44,33 +44,44 @@ public class FileController { return ResponseEntity.ok(files); } - @GetMapping("/{fileId}") - @PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)") + @GetMapping("/{file_id}") + @PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)") public ResponseEntity getById(@PathVariable("file_id") UUID fileId) { File file = fileService.getById(fileId); return ResponseEntity.ok(file); } - @PostMapping + @PostMapping(consumes = "multipart/form-data") @PreAuthorize("hasRole('ADMIN') or #uploadedBy == authentication.principal.userId") public ResponseEntity create( - @RequestBody FileDto.Request dto, - @RequestPart("file") MultipartFile file + @RequestPart("file") MultipartFile file, + @RequestPart("fileName") String fileName, + @RequestPart("mimeType") String mimeType, + @RequestPart("uploadedBy") UUID uploadedBy, + @RequestPart("context") Integer context ) throws IOException { - File created = fileService.create(FileMapper.toEntity(dto), file.getBytes()); - return ResponseEntity.status(HttpStatus.CREATED).body(FileMapper.toResponse(created)); + + File entity = new File(); + entity.setFileName(fileName); + entity.setMimeType(mimeType); + entity.setUploadedBy(uploadedBy); + entity.setContext(context.byteValue()); + + File created = fileService.create(entity, file.getBytes()); + return ResponseEntity.status(HttpStatus.CREATED) + .body(FileMapper.toResponse(created)); } - @PutMapping("/{fileId}") - @PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)") - public ResponseEntity update(@PathVariable("fileId") UUID fileId, @RequestBody FileDto.Request request) { + @PutMapping("/{file_id}") + @PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)") + public ResponseEntity update(@PathVariable("file_id") UUID fileId, @RequestBody FileDto.Request request) { File updated = fileService.update(fileId, FileMapper.toEntity(request)); return ResponseEntity.ok(updated); } - @DeleteMapping("/{fileId}") - @PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)") - public ResponseEntity delete(@PathVariable("fileId") UUID fileId, @RequestBody Map body) throws IOException { + @DeleteMapping("/{file_id}") + @PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)") + public ResponseEntity delete(@PathVariable("file_id") UUID fileId, @RequestBody Map body) throws IOException { String filePath = body.get("file_path"); Files.deleteIfExists(Paths.get(filePath)); fileService.delete(fileId); diff --git a/huertos/pom.xml b/huertos/pom.xml index b986b83..4f9636b 100644 --- a/huertos/pom.xml +++ b/huertos/pom.xml @@ -76,7 +76,7 @@ net.miarma backlib - 1.0.1 + 1.1.0 compile diff --git a/huertos/src/main/java/net/miarma/backend/huertos/client/CoreAuthClient.java b/huertos/src/main/java/net/miarma/backend/huertos/client/CoreAuthClient.java index 03a13ec..1808fbc 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/client/CoreAuthClient.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/client/CoreAuthClient.java @@ -1,9 +1,12 @@ package net.miarma.backend.huertos.client; +import net.miarma.backlib.dto.ApiErrorDto; import net.miarma.backlib.dto.LoginRequest; import net.miarma.backlib.dto.LoginResponse; +import net.miarma.backlib.exception.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; @@ -25,10 +28,46 @@ public class CoreAuthClient { public LoginResponse login(LoginRequest req) { - return restTemplate.postForObject( - coreUrl + "/auth/login", - req, - LoginResponse.class + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity requestEntity = new HttpEntity<>(req, headers); + + ResponseEntity response = restTemplate.exchange( + coreUrl + "/auth/login", + HttpMethod.POST, + requestEntity, + LoginResponse.class ); + + if (!response.getStatusCode().is2xxSuccessful()) { + handleError(response); + } + + return response.getBody(); + } + + private void handleError(ResponseEntity response) { + HttpStatusCode statusCode = response.getStatusCode(); + + if (statusCode.equals(HttpStatus.UNAUTHORIZED)) { + throw new UnauthorizedException("Credenciales no válidas"); + } else if (statusCode.equals(HttpStatus.FORBIDDEN)) { + throw new ForbiddenException("Esa cuenta está desactivada"); + } else if (statusCode.equals(HttpStatus.NOT_FOUND)) { + throw new NotFoundException("No encontrado"); + } else if (statusCode.equals(HttpStatus.BAD_REQUEST)) { + throw new BadRequestException("Datos de solicitud faltantes"); + } else if (statusCode.equals(HttpStatus.CONFLICT)) { + throw new ConflictException("Ya existe"); + } else if (statusCode.equals(HttpStatus.UNPROCESSABLE_CONTENT)) { + throw new ValidationException("general", "Los datos no tienen formato válido"); + } else { + if (statusCode.is4xxClientError()) { + throw new BadRequestException(response.getBody().toString()); + } else { + throw new RuntimeException("Error desconocido"); + } + } } } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/client/HuertosWebClient.java b/huertos/src/main/java/net/miarma/backend/huertos/client/HuertosWebClient.java index dae7ed5..b7650cf 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/client/HuertosWebClient.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/client/HuertosWebClient.java @@ -4,11 +4,14 @@ import net.miarma.backend.huertos.dto.RequestMetadataDto; import net.miarma.backend.huertos.model.RequestMetadata; import net.miarma.backend.huertos.util.UsernameGenerator; import net.miarma.backlib.dto.*; +import net.miarma.backlib.exception.*; import net.miarma.backlib.security.PasswordGenerator; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; +import tools.jackson.databind.ObjectMapper; import java.util.Arrays; import java.util.List; @@ -19,85 +22,170 @@ public class HuertosWebClient { private final RestTemplate restTemplate; private final String coreUrl; + private final ObjectMapper objectMapper; public HuertosWebClient(@Qualifier("secureRestTemplate") RestTemplate restTemplate, - @Value("${core.url}") String coreUrl) { + @Value("${core.url}") String coreUrl, + ObjectMapper objectMapper) { this.restTemplate = restTemplate; this.coreUrl = coreUrl; + this.objectMapper = objectMapper; } public UserWithCredentialDto getUserWithCredential(UUID userId, Byte serviceId) { - return restTemplate.getForObject( + ResponseEntity response = restTemplate.exchange( coreUrl + "/users/{user_id}/service/{service_id}", + HttpMethod.GET, + null, UserWithCredentialDto.class, userId, serviceId ); + + if (!response.getStatusCode().is2xxSuccessful()) { + handleError(response); + } + + return response.getBody(); } public List getAllUsersWithCredentials(Byte serviceId) { - UserWithCredentialDto[] arr = restTemplate.getForObject( - coreUrl + "/users/service/{service_id}", - UserWithCredentialDto[].class, - serviceId + ResponseEntity response = restTemplate.exchange( + coreUrl + "/users/service/{service_id}", + HttpMethod.GET, + null, + UserWithCredentialDto[].class, + serviceId ); + if (!response.getStatusCode().is2xxSuccessful()) { + handleError(response); + } + + UserWithCredentialDto[] arr = response.getBody(); return arr == null ? List.of() : Arrays.asList(arr); } - public UserWithCredentialDto createUser( - RequestMetadataDto metadataDto - ) { - + public UserWithCredentialDto createUser(RequestMetadataDto metadataDto) { + // 1. Crear el usuario CreateUserDto userDto = new CreateUserDto(metadataDto.displayName(), null); - UserDto createdUser = restTemplate.postForObject( - coreUrl + "/users", - userDto, - UserDto.class + HttpEntity userRequestEntity = new HttpEntity<>(userDto); + + ResponseEntity userResponse = restTemplate.exchange( + coreUrl + "/users", + HttpMethod.POST, + userRequestEntity, + UserDto.class ); - if (createdUser == null) + if (!userResponse.getStatusCode().is2xxSuccessful()) { + handleError(userResponse); + } + + UserDto createdUser = userResponse.getBody(); + if (createdUser == null) { throw new RuntimeException("No se pudo crear al usuario"); + } CreateCredentialDto credDto = new CreateCredentialDto( - createdUser.getUserId(), - (byte)1, - UsernameGenerator.generate(metadataDto.displayName(), metadataDto.memberNumber()), - metadataDto.email(), - PasswordGenerator.generate(8), - (byte)1 - ); - CredentialDto createdCred = restTemplate.postForObject( - coreUrl + "/credentials", - credDto, - CredentialDto.class + createdUser.getUserId(), + (byte) 1, + UsernameGenerator.generate(metadataDto.displayName(), metadataDto.memberNumber()), + metadataDto.email(), + PasswordGenerator.generate(8), + (byte) 1 ); - if (createdCred == null) + HttpEntity credRequestEntity = new HttpEntity<>(credDto); + + ResponseEntity credResponse = restTemplate.exchange( + coreUrl + "/credentials", + HttpMethod.POST, + credRequestEntity, + CredentialDto.class + ); + + if (!credResponse.getStatusCode().is2xxSuccessful()) { + handleError(credResponse); + } + + CredentialDto createdCred = credResponse.getBody(); + if (createdCred == null) { throw new RuntimeException("No se pudo crear la cuenta del usuario"); + } return new UserWithCredentialDto(createdUser, createdCred); } public void deleteUser(UUID userId) { - try { - restTemplate.delete(coreUrl + "/users/{user_id}", userId); - } catch (Exception e) { } + ResponseEntity response = restTemplate.exchange( + coreUrl + "/users/{user_id}", + HttpMethod.DELETE, + null, + Void.class, + userId + ); + + if (!response.getStatusCode().is2xxSuccessful()) { + if (response.getStatusCode() != HttpStatus.NOT_FOUND) { + handleError(response); + } + } } public Byte getCredentialStatus(UUID userId, Byte serviceId) { - return restTemplate.getForObject( + ResponseEntity response = restTemplate.exchange( coreUrl + "/credentials/{service_id}/{user_id}/status", + HttpMethod.GET, + null, Byte.class, serviceId, userId ); + + if (!response.getStatusCode().is2xxSuccessful()) { + handleError(response); + } + + return response.getBody(); } public void updateCredentialStatus(UUID userId, Byte serviceId, Byte newStatus) { ChangeStatusRequest req = new ChangeStatusRequest(newStatus); - restTemplate.put( + HttpEntity requestEntity = new HttpEntity<>(req); + + ResponseEntity response = restTemplate.exchange( coreUrl + "/credentials/{service_id}/{user_id}/status", - req, + HttpMethod.PUT, + requestEntity, + Void.class, serviceId, userId ); + + if (!response.getStatusCode().is2xxSuccessful()) { + handleError(response); + } + } + + private void handleError(ResponseEntity response) { + HttpStatusCode statusCode = response.getStatusCode(); + + if (statusCode.equals(HttpStatus.UNAUTHORIZED)) { + throw new UnauthorizedException("Credenciales no válidas"); + } else if (statusCode.equals(HttpStatus.FORBIDDEN)) { + throw new ForbiddenException("Esa cuenta está desactivada"); + } else if (statusCode.equals(HttpStatus.NOT_FOUND)) { + throw new NotFoundException("No encontrado"); + } else if (statusCode.equals(HttpStatus.BAD_REQUEST)) { + throw new BadRequestException("Datos de solicitud faltantes"); + } else if (statusCode.equals(HttpStatus.CONFLICT)) { + throw new ConflictException("Ya existe"); + } else if (statusCode.equals(HttpStatus.UNPROCESSABLE_CONTENT)) { + throw new ValidationException("general", "Los datos no tienen formato válido"); + } else { + if (statusCode.is4xxClientError()) { + throw new BadRequestException(response.getBody().toString()); + } else { + throw new RuntimeException("Error desconocido"); + } + } } } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/config/CorsConfig.java b/huertos/src/main/java/net/miarma/backend/huertos/config/CorsConfig.java deleted file mode 100644 index 0b5d0f2..0000000 --- a/huertos/src/main/java/net/miarma/backend/huertos/config/CorsConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.miarma.backend.huertos.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class CorsConfig { - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins( - "http://localhost:3000" - ) - .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") - .allowedHeaders("*") - .allowCredentials(true); - } - }; - } -} - diff --git a/huertos/src/main/java/net/miarma/backend/huertos/config/RestTemplateConfig.java b/huertos/src/main/java/net/miarma/backend/huertos/config/RestTemplateConfig.java index ef07032..73bbbea 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/config/RestTemplateConfig.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/config/RestTemplateConfig.java @@ -1,10 +1,13 @@ package net.miarma.backend.huertos.config; +import io.jsonwebtoken.io.IOException; import net.miarma.backend.huertos.service.CoreAuthService; import net.miarma.backlib.security.CoreAuthTokenHolder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; @@ -15,20 +18,31 @@ public class RestTemplateConfig { @Bean public RestTemplate authRestTemplate() { - return new RestTemplate(); + RestTemplate restTemplate = new RestTemplate(); + restTemplate.setErrorHandler(new NoOpResponseErrorHandler()); + return restTemplate; } @Bean public RestTemplate secureRestTemplate(CoreAuthService coreAuthService) { - RestTemplate rt = new RestTemplate(); + RestTemplate restTemplate = new RestTemplate(); - rt.getInterceptors().add((request, body, execution) -> { + restTemplate.getInterceptors().add((request, body, execution) -> { String token = coreAuthService.getToken(); request.getHeaders().setBearerAuth(token); return execution.execute(request, body); }); - return rt; + restTemplate.setErrorHandler(new NoOpResponseErrorHandler()); + + return restTemplate; + } + + public static class NoOpResponseErrorHandler implements ResponseErrorHandler { + @Override + public boolean hasError(ClientHttpResponse response) throws IOException { + return false; + } } } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java b/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java index 67349ea..9cabcfc 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java @@ -5,18 +5,12 @@ import net.miarma.backlib.http.RestAccessDeniedHandler; import net.miarma.backlib.http.RestAuthEntryPoint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; - -import java.util.List; @Configuration @EnableWebSecurity @@ -37,23 +31,9 @@ public class SecurityConfig { this.accessDeniedHandler = accessDeniedHandler; } - @Bean - public CorsConfigurationSource corsConfigurationSource() { - CorsConfiguration config = new CorsConfiguration(); - config.setAllowedOrigins(List.of("http://localhost:3000")); - config.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS")); - config.setAllowedHeaders(List.of("*")); - config.setAllowCredentials(true); - - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", config); - return source; - } - @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http - .cors(Customizer.withDefaults()) .csrf(csrf -> csrf.disable()) .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling(ex -> ex