0%
Microservices Security

Security

Securing microservices with Spring Security and OAuth2

10-15 min

Securing Microservices with Spring Security and OAuth2

Security is a crucial aspect of microservices architectures. Spring Security and OAuth2 make it possible to implement robust authentication and authorization.

1. Configuring the Authorization Server

1.1 Creating the Auth Server Project

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 Server Configuration

# 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 Security Configuration

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

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!