InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
Securing REST Endpoints
You have developed multiple REST APIs and need to secure them from unauthorized access.
Question:
How would you secure REST endpoints in a Spring Boot application? Explain the security mechanism and implementation approach.
To secure REST endpoints in a Spring Boot application, follow these simple steps:
1: Add Spring Security Dependency
Include spring-boot-starter-security in your project’s pom.xml or build.gradle.
2: Configure Security Rules
- Create a class (e.g., SecurityConfig) and extend WebSecurityConfigurerAdapter.
- Override the configure(HttpSecurity http) method to specify which endpoints require authentication.
3: Use Authentication
By default, Spring Security uses basic authentication. You can also use JWT (JSON Web Token) or OAuth2 for more secure options.
4: Set Up User Details
Define users and roles in memory or connect to a database for user management.
Example Implementation:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public").permitAll() // open endpoint
.antMatchers("/api/secure").authenticated() // secured endpoint
.and()
.httpBasic(); // enables basic authentication
}
}
Summary:
1: Add Spring Security
2: Configure which endpoints are secure
3: Use authentication (Basic, JWT, OAuth2)
4: Manage users and roles
This way, only authorized users can access your REST APIs, keeping them safe from unauthorized access.