0%
Segurança de Microsserviços

Segurança

Segurança de microsserviços com Spring Security e OAuth2

10-15 min

Segurança de Microsserviços com Spring Security e OAuth2

A segurança é um aspecto crucial das arquiteturas de microsserviços. O Spring Security e o OAuth2 permitem implementar uma autenticação e uma autorização robustas.

1. Configuração do Servidor de Autorização

1.1 Criação do Projeto 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 Configuração do 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 Configuração da Segurança

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

Comentários

Os comentários são alimentados pelo GitHub Discussions

Conecte-se com o GitHub para participar da discussão

Link copiado!