Skip to content

Protection

Spring Security provide out of the box protection against some exploits.

CSRF

Spring provides protection from Cross Site Request Forgery by ensuring a request comes from trusted website. The one strategy is based on randomly generated CSRF token which is sent along with session cookie by browser.

Using tokens instead of cookies in stateless REST APIs can inherently mitigate CSRF attacks, as the browser does not automatically send the token.

CORS

Cross-origin resource sharing (CORS) is a mechanism to safely bypass the same-origin policy. If Resource server sits on different domain from client application domain, you can configure CORS policy. For instance web browser denies by default cross origin request: portal.domain-a.com -> service.domain-b.com You need to control same origin policy by CORS config. CORS is controlled by HTTP headers: -> Origin, <- Access-Control-Allow-Origin. You can configure the CORS details in configuration class as following:

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://localhost:8443", "http://localhost:8080"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
        configuration.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
 ```   

-----
* https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html

## HTTPS redirect

```java
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig {

        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http
            // ...
                .requiresChannel(channel -> channel
                    .anyRequest().requiresSecure()
                );
            return http.build();
        }
    }

HTTP Headers

Spring Security handles some default HTTP headers which are considered as the best practices for web applications security improvement.

    Cache-Control: no-cache, no-store, max-age=0, must-revalidate
    Pragma: no-cache
    Expires: 0
    X-Content-Type-Options: nosniff
    Strict-Transport-Security: max-age=31536000 ; includeSubDomains
    X-Frame-Options: DENY
    X-XSS-Protection: 0
  • Disable caching
  • Content sniffing disabling to stop browsers to guess content type of request and potential XSS attack
  • Strict transport security - HSTS to avoid main in the middle attacks by enabling web sites to declare themselves accessible only via secure connections
  • Protection against click-jacking to disable page rendering in frame (X-Frame-Options: DENY)
  • Refer Spring doc for more