Bird
Raised Fist0
Spring Bootframework~8 mins

CORS configuration in Security in Spring Boot - Performance & Optimization

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Performance: CORS configuration in Security
MEDIUM IMPACT
This affects how quickly the browser can safely load resources from different origins without blocking or delays.
Allowing cross-origin requests in a Spring Boot app
Spring Boot
http.cors().configurationSource(request -> {
  CorsConfiguration config = new CorsConfiguration();
  config.setAllowedOrigins(List.of("https://example.com"));
  config.setAllowedMethods(List.of("GET", "POST"));
  config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
  config.setAllowCredentials(true);
  return config;
});
Explicitly defining allowed origins and methods reduces unnecessary preflight requests and speeds up resource loading.
📈 Performance GainReduces preflight requests, improving LCP by avoiding blocking network calls.
Allowing cross-origin requests in a Spring Boot app
Spring Boot
http.cors().and().csrf().disable(); // No specific CORS config, defaults apply
Using default or no CORS configuration causes browsers to send preflight OPTIONS requests that may be rejected or delayed.
📉 Performance CostTriggers extra preflight requests causing delays in resource loading and blocking rendering.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Default or no CORS configN/AN/ABlocks rendering until preflight completes[X] Bad
Explicit CORS config with limited origins and methodsN/AN/AAllows faster resource loading, no blocking[OK] Good
Rendering Pipeline
When a browser requests a cross-origin resource, it may send a preflight OPTIONS request to check permissions before the actual request. Proper CORS config lets the server respond quickly and correctly, allowing the browser to proceed without delay.
Network Request
Resource Loading
Rendering
⚠️ BottleneckNetwork Request due to preflight OPTIONS calls
Core Web Vital Affected
LCP
This affects how quickly the browser can safely load resources from different origins without blocking or delays.
Optimization Tips
1Always specify allowed origins and methods explicitly in CORS config.
2Avoid wildcard '*' origins when credentials are needed to reduce preflight requests.
3Use minimal allowed headers to prevent unnecessary preflight checks.
Performance Quiz - 3 Questions
Test your performance knowledge
What impact does missing or default CORS configuration have on page load?
AImproves page load by caching all resources
BHas no impact on page load speed
CCauses extra preflight requests that delay resource loading
DReduces network requests by combining them
DevTools: Network
How to check: Open DevTools > Network tab, filter by OPTIONS requests, reload page and observe if preflight requests occur and their timing.
What to look for: Look for OPTIONS requests before actual resource requests; fewer or faster OPTIONS requests indicate better CORS performance.

Practice

(1/5)
1. What is the main purpose of configuring CORS in a Spring Boot security setup?
easy
A. To control which external websites can access your backend resources
B. To improve database query performance
C. To manage user authentication tokens
D. To style the frontend user interface

Solution

  1. Step 1: Understand CORS role in web security

    CORS (Cross-Origin Resource Sharing) controls which external domains can call your backend APIs.
  2. Step 2: Identify the purpose in Spring Boot security

    Configuring CORS in Spring Security allows safe cross-site requests by specifying allowed origins and methods.
  3. Final Answer:

    To control which external websites can access your backend resources -> Option A
  4. Quick Check:

    CORS controls access origins = A [OK]
Hint: CORS = Cross-Origin access control [OK]
Common Mistakes:
  • Confusing CORS with authentication
  • Thinking CORS improves database speed
  • Assuming CORS styles frontend
2. Which of the following is the correct way to enable CORS in a Spring Security configuration class?
easy
A. http.corsEnabled(true);
B. http.enableCors();
C. http.allowCors(true);
D. http.cors().and().csrf().disable();

Solution

  1. Step 1: Recall Spring Security CORS enabling syntax

    Spring Security uses the method http.cors() to enable CORS support.
  2. Step 2: Identify the correct chaining method

    The correct chaining to disable CSRF and enable CORS is http.cors().and().csrf().disable();
  3. Final Answer:

    http.cors().and().csrf().disable(); -> Option D
  4. Quick Check:

    Enable CORS with http.cors() = C [OK]
Hint: Use http.cors() to enable CORS in Spring Security [OK]
Common Mistakes:
  • Using non-existent methods like enableCors()
  • Forgetting to chain with .and()
  • Confusing CORS enabling with CSRF
3. Given this Spring Security CORS configuration snippet, what origins are allowed?
@Bean
public CorsConfigurationSource corsConfigurationSource() {
  CorsConfiguration configuration = new CorsConfiguration();
  configuration.setAllowedOrigins(List.of("https://example.com", "https://app.example.com"));
  configuration.setAllowedMethods(List.of("GET", "POST"));
  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  source.registerCorsConfiguration("/**", configuration);
  return source;
}
medium
A. No origins are allowed because configuration is incomplete
B. Requests from any origin are allowed
C. Only requests from https://example.com and https://app.example.com are allowed
D. Only GET requests from any origin are allowed

Solution

  1. Step 1: Analyze allowed origins list

    The code sets allowed origins explicitly to "https://example.com" and "https://app.example.com".
  2. Step 2: Understand effect on requests

    Only requests coming from these two origins will be accepted; others will be blocked by CORS policy.
  3. Final Answer:

    Only requests from https://example.com and https://app.example.com are allowed -> Option C
  4. Quick Check:

    Allowed origins = example.com and app.example.com = D [OK]
Hint: Allowed origins list controls which sites can call backend [OK]
Common Mistakes:
  • Assuming all origins allowed by default
  • Confusing allowed methods with allowed origins
  • Thinking configuration is incomplete without headers
4. Identify the error in this Spring Security CORS configuration code:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
  CorsConfiguration configuration = new CorsConfiguration();
  configuration.setAllowedOrigins("*");
  configuration.setAllowedMethods(List.of("GET", "POST"));
  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  source.registerCorsConfiguration("/**", configuration);
  return source;
}
medium
A. Allowed methods list is missing PUT and DELETE
B. setAllowedOrigins expects a list, not a single string
C. UrlBasedCorsConfigurationSource cannot be used here
D. The method should return void, not CorsConfigurationSource

Solution

  1. Step 1: Check setAllowedOrigins parameter type

    The method setAllowedOrigins requires a List<String>, but the code passes a single String "*".
  2. Step 2: Understand correct usage for wildcard

    To allow all origins, use List.of("*") instead of a plain string.
  3. Final Answer:

    setAllowedOrigins expects a list, not a single string -> Option B
  4. Quick Check:

    Allowed origins must be List<String> = B [OK]
Hint: setAllowedOrigins needs a list, not a string [OK]
Common Mistakes:
  • Passing a string instead of a list to setAllowedOrigins
  • Ignoring method parameter types
  • Assuming missing HTTP methods cause errors here
5. You want to allow all origins but only GET and POST methods in your Spring Security CORS config. Which code snippet correctly achieves this while following best practices?
hard
A. configuration.setAllowedOriginPatterns(List.of("*")); configuration.setAllowedMethods(List.of("GET", "POST"));
B. configuration.setAllowedOrigins(List.of("*")); configuration.setAllowedMethods(List.of("GET", "POST"));
C. configuration.setAllowedOrigins("*"); configuration.setAllowedMethods(List.of("GET", "POST"));
D. configuration.setAllowedOrigins(List.of("*")); configuration.setAllowedMethods(List.of("GET", "POST", "PUT"));

Solution

  1. Step 1: Understand wildcard origin allowance

    Using setAllowedOrigins(List.of("*")) is deprecated and may cause issues; instead, setAllowedOriginPatterns supports wildcards properly.
  2. Step 2: Check allowed methods correctness

    Only GET and POST methods are allowed as required.
  3. Final Answer:

    configuration.setAllowedOriginPatterns(List.of("*")); configuration.setAllowedMethods(List.of("GET", "POST")); -> Option A
  4. Quick Check:

    Use allowedOriginPatterns for wildcard origins = A [OK]
Hint: Use setAllowedOriginPatterns for wildcard origins [OK]
Common Mistakes:
  • Using setAllowedOrigins with "*" string
  • Allowing extra HTTP methods by mistake
  • Passing string instead of list to allowed origins