blob: d91c52aa1f2b0b52f23018ecb5be1e7590ac74de (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package com.example.resourceserver.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
/**
* This filter chain allows H2 database console access.
*
* To disable this filter chain, just disable h2 console in application.yaml
*
* To access h2 console:
* http://localhost:8052/myservices/h2-console
*
* @param http
* @return
* @throws Exception
*/
@Bean
@Order(1) // Ensures this filter chain is evaluated first
@ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true", matchIfMissing = false)
public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatcher(PathRequest.toH2Console()) // Targets only the H2 console path
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) // Allows public access
.csrf(csrf -> csrf.disable()) // Disables CSRF protection for H2 console
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); // Allows iframe rendering
// from same origin
return http.build();
}
@Bean
@Order(2) // Evaluated after the H2 console filter chain
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
// 1. Specify the URL to allow without restrictions
.requestMatchers("/security/open/users/*/roles", "/public/**").permitAll()
// 2. Require authentication for all other requests
.anyRequest().authenticated())
// 3. Configure the app as an OAuth2 Resource Server
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults()));
return http.build();
}
}
|