59 lines
2.4 KiB
Java
59 lines
2.4 KiB
Java
package com.example.keycloakpattern;
|
|
|
|
import java.util.List;
|
|
|
|
import org.springframework.context.annotation.Bean;
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.security.config.Customizer;
|
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
|
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
|
import org.springframework.security.web.SecurityFilterChain;
|
|
import org.springframework.web.cors.CorsConfiguration;
|
|
import org.springframework.web.cors.CorsConfigurationSource;
|
|
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
|
|
|
@Configuration
|
|
public class SecurityConfig {
|
|
|
|
@Bean
|
|
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
|
|
return http
|
|
.cors(Customizer.withDefaults())
|
|
.csrf(csrf -> csrf.disable())
|
|
.sessionManagement(session ->
|
|
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
|
.authorizeHttpRequests(authorize -> authorize
|
|
.requestMatchers("/actuator/health", "/actuator/health/**", "/api/public")
|
|
.permitAll()
|
|
.requestMatchers("/api/admin")
|
|
.hasRole("admin-role")
|
|
.anyRequest()
|
|
.authenticated())
|
|
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt ->
|
|
jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())))
|
|
.build();
|
|
}
|
|
|
|
private JwtAuthenticationConverter jwtAuthenticationConverter() {
|
|
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
|
|
converter.setJwtGrantedAuthoritiesConverter(new KeycloakRealmRoleConverter());
|
|
return converter;
|
|
}
|
|
|
|
@Bean
|
|
CorsConfigurationSource corsConfigurationSource() {
|
|
CorsConfiguration configuration = new CorsConfiguration();
|
|
configuration.setAllowedOrigins(List.of(
|
|
"http://localhost:8088",
|
|
"http://127.0.0.1:8088"
|
|
));
|
|
configuration.setAllowedMethods(List.of("GET", "OPTIONS"));
|
|
configuration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
|
|
|
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
|
source.registerCorsConfiguration("/api/**", configuration);
|
|
return source;
|
|
}
|
|
}
|