Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Spring Security and CORS

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to restrict how resources on a web page can be requested from another domain. This guide covers key concepts and steps for enabling and configuring CORS in your Spring Boot application, including adding dependencies, configuring CORS settings, and securing endpoints.

Key Concepts of CORS

  • CORS (Cross-Origin Resource Sharing): A security feature that restricts how resources on a web page can be requested from another domain.
  • CORS Configuration: Configuring Spring Security to allow cross-origin requests.
  • Security Configuration: Ensuring that CORS settings are properly integrated with Spring Security.

Adding Dependencies

Include the Spring Security dependency in your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Enabling and Configuring CORS

Enable and configure CORS by creating a global CORS configuration class:

Example: WebConfig.java

// WebConfig.java
package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        };
    }
}

Configuring CORS with Spring Security

Integrate CORS configuration with Spring Security settings:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
package com.example.myapp.config;

import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home", true)
            .failureUrl("/login?error=true")
            .and()
            .logout()
            .logoutSuccessUrl("/login?logout=true")
            .permitAll();
    }
}

Enabling CORS on Specific Endpoints

Alternatively, enable CORS on specific endpoints using the @CrossOrigin annotation:

Example: MyController.java

// MyController.java
package com.example.myapp.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/greeting")
    public String greeting() {
        return "Hello, World!";
    }
}

Testing CORS Configuration

Test your CORS configuration using tools like Postman or a web application hosted on a different origin:

Example: Testing with curl

$ curl -H "Origin: http://localhost:3000" --verbose http://localhost:8080/greeting

Key Points

  • CORS (Cross-Origin Resource Sharing): A security feature that restricts how resources on a web page can be requested from another domain.
  • CORS Configuration: Configuring Spring Security to allow cross-origin requests.
  • Security Configuration: Ensuring that CORS settings are properly integrated with Spring Security.
  • Include the Spring Security dependency in your pom.xml file.
  • Enable and configure CORS by creating a global CORS configuration class.
  • Integrate CORS configuration with Spring Security settings.
  • Alternatively, enable CORS on specific endpoints using the @CrossOrigin annotation.
  • Test your CORS configuration using tools like Postman or a web application hosted on a different origin.

Conclusion

Configuring CORS is essential for enabling secure cross-origin requests in your Spring Boot application. By understanding and implementing CORS settings, integrating them with Spring Security, and testing your configuration, you can ensure that your application allows legitimate cross-origin requests while protecting against unauthorized access. Happy coding!