As soon as you add Spring Security to a Spring Boot project, every endpoint asks for a login. That surprises many beginners. Understanding a few core ideas turns it from a mystery into a tool.
Authentication vs authorisation
- Authentication: who are you? Checking a username and password, or a token.
- Authorisation: what are you allowed to do? For example, only ADMIN users may delete courses.
The security filter chain
Every request passes through a chain of filters before reaching your controller. You configure that chain with a SecurityFilterChain bean:
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/courses/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
Disabling CSRF is common for stateless APIs that use tokens; keep it enabled for browser forms with sessions.
Storing passwords
Never store plain passwords. Use a PasswordEncoder bean such as BCryptPasswordEncoder, and load users from your database by implementing UserDetailsService.
Tokens and JWT
Many APIs use JSON Web Tokens: the user logs in once, receives a signed token, and sends it in the Authorization: Bearer header on each request. Spring Security’s OAuth2 resource server support validates such tokens. Keep token lifetimes short and the signing key secret.
Common beginner problems
- Every request returns 401: no rule permits the endpoint, or credentials are missing.
- 403 on POST requests: CSRF is still enabled for an API client.
- Roles not matching:
hasRole("ADMIN")expects the stored authority to beROLE_ADMIN.
Related: Spring Boot: your first REST API, Spring Boot exception handling and Spring Boot profiles.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
