Skip to content

Commit

Permalink
feat: Add conditional security configuration based on application pro…
Browse files Browse the repository at this point in the history
…perty

Add a conditional configuration to `SecurityConfiguration` class based on the value of the `spring.security.enabled` property. If security is enabled, configure the application with a resource server using Spring Security, allowing access to Swagger UI endpoints without authentication and requiring authentication for other requests. If security is disabled, authorize all requests without requiring authentication.

Signed-off-by: pierresomny <[email protected]>
  • Loading branch information
pierresomny committed Feb 6, 2024
1 parent 54ffdce commit c340817
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.sfeiropensource.schoolapp.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
Expand All @@ -12,19 +13,35 @@
@Configuration
public class SecurityConfiguration {

@Value("${spring.security.enabled:#{true}")
private String securityEnabled;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configure(http))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(
antMatcher("/v3/api-docs/**"),
antMatcher("/swagger-ui/**")
).permitAll()
.anyRequest().permitAll()
)
.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
// If security is enabled.
if (Boolean.parseBoolean(securityEnabled)) {
// Set-up has a resource server with spring security.
http
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configure(http))
.authorizeHttpRequests(authorize -> authorize
// Authorize swagger freely
.requestMatchers(
antMatcher("/v3/api-docs/**"),
antMatcher("/swagger-ui/**")
).permitAll()
// And other requests authenticated.
.anyRequest().authenticated()
)
.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));

} else {
// Else, authorize all request.
http
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configure(http))
.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll());
}
return http.build();
}
}
3 changes: 2 additions & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
info.api.title[email protected]@
info.api.version[email protected]@
info.api.description[email protected]@
management.endpoint.shutdown.enabled=true
management.endpoint.shutdown.enabled=true
spring.security.enabled=true

0 comments on commit c340817

Please sign in to comment.