-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWebSecurityConfig.java
More file actions
163 lines (144 loc) · 7.58 KB
/
WebSecurityConfig.java
File metadata and controls
163 lines (144 loc) · 7.58 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*
* Copyright 2022 Karlsruhe Institute of Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.kit.datamanager.mappingservice.configuration;
import edu.kit.datamanager.security.filter.KeycloakTokenFilter;
import edu.kit.datamanager.security.filter.NoAuthenticationFilter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
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.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
/**
* @author jejkal
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
@Autowired
private Optional<KeycloakTokenFilter> keycloaktokenFilterBean;
@Autowired
private ApplicationProperties applicationProperties;
private static final String[] AUTH_WHITELIST_SWAGGER_UI = {
// -- Swagger UI v2
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
// -- Swagger UI v3 (OpenAPI)
"/v3/api-docs/**",
"/swagger-ui/**"
// other public endpoints of your API may be appended to this array
};
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
List<AntPathRequestMatcher> securedEndpointMatchers;
if (applicationProperties.isAuthEnabled()) {
logger.trace("Authentication is ENABLED. Collecting secured endpoints.");
securedEndpointMatchers = Arrays.asList(
new AntPathRequestMatcher("/api/v1/mappingAdministration/reloadTypes", "GET"),
new AntPathRequestMatcher("/api/v1/mappingAdministration", "PUT"),
new AntPathRequestMatcher("/api/v1/mappingAdministration", "POST")
);
} else {
logger.trace("Authentication is DISABLED. Not securing endpoints.");
securedEndpointMatchers = Arrays.asList();
}
HttpSecurity httpSecurity = http.authorizeHttpRequests(
authorize -> authorize.
requestMatchers(HttpMethod.OPTIONS).permitAll().
requestMatchers(EndpointRequest.to(
InfoEndpoint.class,
HealthEndpoint.class
)).permitAll().
requestMatchers(EndpointRequest.toAnyEndpoint()).hasAnyRole("ANONYMOUS", "ADMINISTRATOR", "ACTUATOR", "SERVICE_WRITE").
requestMatchers(new AntPathRequestMatcher("/static/**")).permitAll().
requestMatchers(new AntPathRequestMatcher("/error")).permitAll().
requestMatchers(securedEndpointMatchers.toArray(AntPathRequestMatcher[]::new)).hasRole(applicationProperties.getMappingAdminRole()). //endpoint filters only active if auth is enabled
requestMatchers(AUTH_WHITELIST_SWAGGER_UI).permitAll().
anyRequest().authenticated()
).
httpBasic(Customizer.withDefaults()).
cors(cors -> cors.configurationSource(corsConfigurationSource())).
sessionManagement(
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
logger.info("CSRF disabled!");
httpSecurity = httpSecurity.csrf(csrf -> csrf.disable());
if (keycloaktokenFilterBean.isPresent()) {
logger.trace("Adding Keycloak filter to filter chain.");
httpSecurity.addFilterAfter(keycloaktokenFilterBean.get(), BasicAuthenticationFilter.class);
} else {
logger.trace("Keycloak not configured. Skip adding keycloak filter to filter chain.");
}
if (!applicationProperties.isAuthEnabled()) {
logger.info("Adding 'NoAuthenticationFilter' to filter chain.");
AuthenticationManager defaultAuthenticationManager = http.getSharedObject(AuthenticationManager.class);
httpSecurity = httpSecurity.addFilterAfter(new NoAuthenticationFilter("vkfvoswsohwrxgjaxipuiyyjgubggzdaqrcuupbugxtnalhiegkppdgjgwxsmvdb", defaultAuthenticationManager), BasicAuthenticationFilter.class);
} else {
logger.info("Skip adding NoAuthenticationFilter to filter chain.");
}
logger.trace("Turning off cache control.");
httpSecurity.headers(headers -> headers.cacheControl(cache -> cache.disable()));
return httpSecurity.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
}
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern(applicationProperties.getAllowedOriginPattern());
config.setAllowedHeaders(Arrays.asList(applicationProperties.getAllowedHeaders()));
config.setAllowedMethods(Arrays.asList(applicationProperties.getAllowedMethods()));
config.setExposedHeaders(Arrays.asList(applicationProperties.getExposedHeaders()));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}