perf(security): añadido rol al token

parent 55294b1b
......@@ -2,9 +2,14 @@ package com.example.apprecetas.cors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class CorsConfig {
......@@ -16,9 +21,22 @@ public class CorsConfig {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("*")
.allowCredentials(true);
.allowedHeaders("*");
}
};
}
@Bean // Para el securityFilterChain con configuración por defecto
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("http://localhost:5173"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
......@@ -6,6 +6,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
......@@ -26,12 +27,15 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.headers(AbstractHttpConfigurer::disable) // necesario para h2-console
.httpBasic(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> request
// Para autenticación todos permitidos
.requestMatchers("/auth/**").permitAll()
// FRONTEND getAllRecipes
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// Para ver todos los usuarios, solo ADMIN
.requestMatchers(HttpMethod.GET, "/user").hasRole("ADMIN")
// Para eliminar un usuario, solo ADMIN
......@@ -50,5 +54,6 @@ public class SecurityConfig {
return authConfig.getAuthenticationManager();
}
}
......@@ -23,10 +23,11 @@ public class JwtTokenProvider {
private final SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
public String generateToken(String id) {
public String generateToken(String id, String role) {
long jwtExpirationMs = 3600000; // 1 hora en milisegundos
return Jwts.builder()
.subject(id)
.claim("role", role) // Para acceder al rol desde el token
.issuedAt(new Date())
.expiration(Date.from(Instant.now().plus(jwtExpirationMs, ChronoUnit.MILLIS)))
.signWith(secretKey)
......
......@@ -55,7 +55,7 @@ public class AuthController {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Collections.singletonMap("message", "Contraseña incorrecta"));
String token = jwtTokenProvider.generateToken(user.getId());
String token = jwtTokenProvider.generateToken(user.getId(), user.getRole().name());
return ResponseEntity.ok(new AuthResponse(token));
} catch (EntityNotFoundException e) {
......@@ -78,7 +78,7 @@ public class AuthController {
URI location = URI.create("/user");
User createdUser = createUserService.create(mapper.map(userInputDto));
String token = jwtTokenProvider.generateToken(createdUser.getId());
String token = jwtTokenProvider.generateToken(createdUser.getId(), createdUser.getRole().name());
return ResponseEntity.created(location).body(new AuthResponse(token));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment