0% found this document useful (0 votes)
12 views6 pages

Spring Security CORS Configuration Guide

The document outlines key concepts of Spring Security related to CORS and request filtering, including CorsConfiguration, CorsConfigurationSource, and CorsFilter, which manage cross-origin requests. It also explains SecurityFilterChain and HttpSecurity for defining authentication and authorization rules, as well as methods for managing CSRF protection, session handling, and exception handling. Examples are provided for each concept to illustrate their implementation in a Spring application.

Uploaded by

keshavv857
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

Spring Security CORS Configuration Guide

The document outlines key concepts of Spring Security related to CORS and request filtering, including CorsConfiguration, CorsConfigurationSource, and CorsFilter, which manage cross-origin requests. It also explains SecurityFilterChain and HttpSecurity for defining authentication and authorization rules, as well as methods for managing CSRF protection, session handling, and exception handling. Examples are provided for each concept to illustrate their implementation in a Spring application.

Uploaded by

keshavv857
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Spring Security — Deep Notes (Easy Language)

1. What is CorsConfiguration?

CorsConfiguration is a Spring class used to define rules for Cross-Origin Resource Sharing
(CORS).
When your frontend and backend run on different ports or domains, browsers block
requests for safety.
CORS allows trusted domains to communicate with your backend.

Example:
CorsConfiguration config = new CorsConfiguration();
[Link]([Link]("[Link]
[Link]([Link]("GET", "POST", "PUT", "DELETE"));
[Link]([Link]("*"));
[Link](true);

This allows the frontend running on port 3000 to communicate with the backend on port
8080.

2. What is CorsConfigurationSource?

CorsConfigurationSource is the provider for CORS rules. It registers your CorsConfiguration


with URL patterns.

Example:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
[Link]([Link]("[Link]
[Link]([Link]("GET", "POST", "PUT", "DELETE"));
[Link]([Link]("*"));
[Link](true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
[Link]("/**", config);
return source;
}
Think of CorsConfiguration as the rules, and CorsConfigurationSource as the registration
point.

3. What is CorsFilter?

CorsFilter is a Spring filter class that automatically applies CORS rules to all incoming
requests.
It ensures that requests from unauthorized origins are blocked with a 403 Forbidden
response.

Example:
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
[Link]("[Link]
[Link]("*");
[Link]("*");
[Link]("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new
CorsFilter(source));
[Link](0);
return bean;
}

Modern Spring Boot automatically applies CorsFilter when you use [Link]().

4. Are these the only CORS-related classes?


Class Description

CorsConfiguration Defines allowed origins, headers, and


methods.

CorsConfigurationSource Registers the configuration with URL


patterns.

CorsFilter Applies the CORS rules to incoming


requests automatically.

5. What is SecurityFilterChain?

SecurityFilterChain defines how requests are filtered for authentication and authorization
in Spring Security.
Each HTTP request passes through this chain before reaching controllers.

Example:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
[Link](auth -> auth
.requestMatchers("/", "/register", "/login").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").authenticated()
.anyRequest().denyAll()
)
.csrf(csrf -> [Link]())
.cors(cors -> [Link](corsConfigurationSource()));
return [Link]();
}

6. What is HttpSecurity?

HttpSecurity is the main configuration object that controls security settings for HTTP
requests.
You use it inside your SecurityFilterChain to define access rules, authentication type, CORS,
and CSRF policies.

Example:
http
.authorizeHttpRequests(auth -> ...)
.formLogin(form -> ...)
.csrf(cs -> [Link]())
.cors(cors -> [Link](corsConfigurationSource()));

7. authorizeHttpRequests() and Sub-functions

authorizeHttpRequests() defines which URLs are accessible and by whom.


It provides several sub-functions to specify access control.

Method Meaning Example


permitAll() Allows public access to the .requestMatchers("/
URL home").permitAll()

authenticated() Allows only logged-in users .requestMatchers("/cart/


**").authenticated()

hasRole("ADMIN") Allows users with ADMIN .requestMatchers("/


role admin/
**").hasRole("ADMIN")

hasAnyRole() Allows users with any of the .requestMatchers("/


specified roles dashboard").hasAnyRole("U
SER", "ADMIN")

hasAuthority() Allows access with a .requestMatchers("/


specific permission reports").hasAuthority("PE
RM_READ")

hasAnyAuthority() Allows access with any .requestMatchers("/edit/


listed permission **").hasAnyAuthority("PER
M_EDIT", "PERM_DELETE")

denyAll() Denies access to everyone .requestMatchers("/


private").denyAll()

anyRequest() Applies rule to all .anyRequest().authenticated


unmatched routes ()

8. csrf()

CSRF (Cross-Site Request Forgery) is used to protect against attacks in HTML form-based
applications.
For REST APIs that use JWT tokens, it is generally disabled.

Example:
[Link](csrf -> [Link]());

9. cors()

This enables frontend-backend communication through the CORS rules defined earlier.
Example:
[Link](cors -> [Link](corsConfigurationSource()));

10. formLogin() and logout()

Used when the application has its own login form rather than JWT-based login.

Example:
[Link](form -> form
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
)
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
);

11. sessionManagement()

Controls how sessions are handled.


For JWT-based applications, sessions are stateless (not stored on the server).

Example:
[Link](session -> session
.sessionCreationPolicy([Link])
);

12. exceptionHandling()

Defines how exceptions like unauthorized access or forbidden pages are handled.

Example:
[Link](ex -> [Link]("/access-denied"));
Summary Table
Concept Purpose Example

CorsConfiguration Defines allowed origins, Backend <-> Frontend link


headers, and methods

CorsConfigurationSource Registers rules with URL [Link]


patterns ation("/**", config)

CorsFilter Applies CORS rules to Automatically enabled via


incoming requests [Link]()

SecurityFilterChain Defines full security flow [Link]


()

HttpSecurity Main configuration object [Link]().disable()

authorizeHttpRequests() Defines access control requestMatchers("/


admin/
**").hasRole("ADMIN")

csrf() Protect forms / disable for JWT-based → disable


APIs

cors() Allow frontend-backend React + Spring


communication

sessionManagement() Manage user sessions Stateless for JWT

exceptionHandling() Handle access denied Redirect or custom message

You might also like