0%
Sécurité des Microservices

Sécurité

Sécurité des microservices avec Spring Security et OAuth2

10-15 min

Sécurité des Microservices avec Spring Security et OAuth2

La sécurité est un aspect crucial des architectures microservices. Spring Security et OAuth2 permettent de mettre en place une authentification et une autorisation robustes.

1. Configuration du Serveur d'Authorization

1.1 Création du Projet 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 Configuration du Serveur

# 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 Configuration de la Sécurité

@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;
    }
}

Commentaires

Les commentaires sont alimentés par GitHub Discussions

Connectez-vous avec GitHub pour participer à la discussion

Lien copié !