Seguridad
Seguridad de los microservicios con Spring Security y OAuth2
10-15 min
Seguridad de los Microservicios con Spring Security y OAuth2
La seguridad es un aspecto crucial de las arquitecturas de microservicios. Spring Security y OAuth2 permiten implantar una autenticación y una autorización robustas.
1. Configuración del servidor de autorización
1.1 Creación del proyecto Auth Server
curl https://start.spring.io/starter.tgz \
-d dependencies=oauth2-resource-server,oauth2-authorization-server \
-d groupId=com.example \
-d artifactId=auth-server \
-d name=auth-server \
-d description=OAuth2%20Authorization%20Server \
-d packageName=com.example.auth \
-d packaging=jar \
-d javaVersion=17 \
-d type=maven-project \
| tar -xzvf -
1.2 Configuración del servidor
# application.yml
server:
port: 9000
spring:
application:
name: auth-server
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9000
jwk-set-uri: http://localhost:9000/.well-known/jwks.json
1.3 Configuración de la seguridad
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/oauth2/**", "/login/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(jwtAuthenticationConverter())
)
)
.build();
}
@Bean
public Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(jwt -> {
List<String> roles = jwt.getClaimAsStringList("roles");
return roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toList());
});
return jwtConverter;
}
}
Comentarios
Los comentarios funcionan con GitHub Discussions
Inicia sesión con GitHub para participar en la discusión