Fix: CORS.
This commit is contained in:
2
TODO
2
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 (?)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>backlib</artifactId>
|
||||
<groupId>net.miarma</groupId>
|
||||
<version>1.0.1</version>
|
||||
<version>1.1.0</version>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
artifactId=backlib
|
||||
groupId=net.miarma
|
||||
version=1.0.1
|
||||
version=1.1.0
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -83,7 +83,7 @@
|
||||
<dependency>
|
||||
<groupId>net.miarma</groupId>
|
||||
<artifactId>backlib</artifactId>
|
||||
<version>1.0.1</version>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<File> 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<FileDto.Response> 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<File> 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<File> 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<Void> delete(@PathVariable("fileId") UUID fileId, @RequestBody Map<String,String> body) throws IOException {
|
||||
@DeleteMapping("/{file_id}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)")
|
||||
public ResponseEntity<Void> delete(@PathVariable("file_id") UUID fileId, @RequestBody Map<String,String> body) throws IOException {
|
||||
String filePath = body.get("file_path");
|
||||
Files.deleteIfExists(Paths.get(filePath));
|
||||
fileService.delete(fileId);
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
<dependency>
|
||||
<groupId>net.miarma</groupId>
|
||||
<artifactId>backlib</artifactId>
|
||||
<version>1.0.1</version>
|
||||
<version>1.1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -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(
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
HttpEntity<LoginRequest> requestEntity = new HttpEntity<>(req, headers);
|
||||
|
||||
ResponseEntity<LoginResponse> response = restTemplate.exchange(
|
||||
coreUrl + "/auth/login",
|
||||
req,
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,44 +22,69 @@ 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<UserWithCredentialDto> 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<UserWithCredentialDto> getAllUsersWithCredentials(Byte serviceId) {
|
||||
UserWithCredentialDto[] arr = restTemplate.getForObject(
|
||||
ResponseEntity<UserWithCredentialDto[]> 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(
|
||||
HttpEntity<CreateUserDto> userRequestEntity = new HttpEntity<>(userDto);
|
||||
|
||||
ResponseEntity<UserDto> userResponse = restTemplate.exchange(
|
||||
coreUrl + "/users",
|
||||
userDto,
|
||||
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(),
|
||||
@@ -66,38 +94,98 @@ public class HuertosWebClient {
|
||||
PasswordGenerator.generate(8),
|
||||
(byte) 1
|
||||
);
|
||||
CredentialDto createdCred = restTemplate.postForObject(
|
||||
|
||||
HttpEntity<CreateCredentialDto> credRequestEntity = new HttpEntity<>(credDto);
|
||||
|
||||
ResponseEntity<CredentialDto> credResponse = restTemplate.exchange(
|
||||
coreUrl + "/credentials",
|
||||
credDto,
|
||||
HttpMethod.POST,
|
||||
credRequestEntity,
|
||||
CredentialDto.class
|
||||
);
|
||||
|
||||
if (createdCred == null)
|
||||
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<Void> 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<Byte> 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<ChangeStatusRequest> requestEntity = new HttpEntity<>(req);
|
||||
|
||||
ResponseEntity<Void> 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user