DEV Community

Poojitha
Poojitha

Posted on

Spring boot Interview Questions

1. What is CORS and why is it required?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that allows/restricts APIs from being accessed by another domain.
Example:
Frontend: http://localhost:3000
Backend API: http://localhost:8080
These are different origins because ports are different.
Without CORS configuration, browser blocks the request.
Why required?
To securely allow frontend applications to call backend APIs hosted on different domains/ports.
Interview Answer:
CORS is a browser security feature that controls cross-origin HTTP requests. It is required when frontend and backend run on different domains, ports, or protocols. In Spring Boot, we configure CORS to allow trusted origins to access APIs securely.
2. How do you configure CORS in Spring Boot?
Using @CrossOrigin
Java
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class UserController {
}
Global Configuration
Java
@Configuration
public class CorsConfig {

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

}
Real-time usage:
In production, React/Angular frontend calls Spring Boot APIs from another domain.

3. What is CSRF attack?
CSRF = Cross Site Request Forgery
It tricks a logged-in user into performing unwanted actions.
Example:
User logged into banking site
Malicious website sends transfer request automatically
Browser sends session cookie
Server thinks request is genuine
Interview Answer:
CSRF attack occurs when a malicious site tricks an authenticated user into sending unauthorized requests to another application where the user is already logged in.

Top comments (0)