Spring Security
Spring Security is the standard library for authentication (who are you?) and authorization (what are you allowed to do?) in Spring applications. You add one starter, declare which URLs need which roles, and Spring Security checks every request before it reaches your controller. It also stores passwords safely, protects forms against CSRF attacks and lets you secure individual service methods.
This lesson uses Spring Boot 4.1 with Spring Security 7, building on the Spring Boot tutorial. All examples are tested with curl against http://localhost:8080.
How Spring Security Works
Spring Security is a chain of servlet filters that runs before the DispatcherServlet. Each filter does one job, such as reading a username and password or checking a role.
| Piece | Job |
|---|---|
SecurityFilterChain | The list of rules and filters applied to matching requests |
UserDetailsService | Loads a user (username, password hash, roles) by username |
PasswordEncoder | Hashes new passwords and checks login attempts against the hash |
Authentication | The logged-in user for the current request |
SecurityContextHolder | Holds the Authentication while the request runs |
Request -> [Security filters: authenticate -> authorize] -> DispatcherServlet -> @RestController
|
+-> 401 Unauthorized (not logged in) or 403 Forbidden (wrong role)
How it works:
- A request that fails a check never reaches your controller, so your business code stays free of security
ifstatements. - 401 means "we don't know who you are". 403 means "we know who you are, but you may not do this".
Add Spring Security to a Spring Boot App
Add the security starter next to the web starter:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
Create a small controller to protect:
package com.gocourse.secure;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/public/hello")
public String hello() {
return "Hello, guest!";
}
@GetMapping("/me")
public String me(@AuthenticationPrincipal UserDetails user) {
return "Hello, " + user.getUsername() + " " + user.getAuthorities();
}
@GetMapping("/admin/stats")
public String stats() {
return "Total students: 1250";
}
}
Start the application without any security configuration. The log shows a generated password:
Using generated security password: 6b1f0c2e-8d4a-4c3e-9a51-2f7d3e9b8c10
This generated password is for development use only. Your security configuration must be updated before running your application in production.
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/public/hello
401
How it works:
- With the starter on the classpath, Spring Boot secures every URL by default. Even the "public" endpoint returns 401.
- Boot creates one user named
userwith a random password printed at startup. You could callcurl -u user:<password> ..., but this default exists only so nothing is left open by accident. - Your real setup always replaces it with a
SecurityFilterChainand your own users, as shown next.
Configure a SecurityFilterChain
A SecurityFilterChain bean tells Spring Security which requests are public, which need a login and which need a role. Spring Security 7 only supports the lambda DSL, where each part is configured inside its own lambda.
package com.gocourse.secure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**", "/error").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
UserDetails asha = User.withUsername("asha")
.password(encoder.encode("asha-pass"))
.roles("STUDENT")
.build();
UserDetails ravi = User.withUsername("ravi")
.password(encoder.encode("ravi-pass"))
.roles("STUDENT", "ADMIN")
.build();
return new InMemoryUserDetailsManager(asha, ravi);
}
}
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/public/hello
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/me
curl -s -u asha:asha-pass http://localhost:8080/api/me; echo
curl -s -o /dev/null -w "%{http_code}\n" -u asha:wrong http://localhost:8080/api/me
curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass http://localhost:8080/api/admin/stats
curl -s -u ravi:ravi-pass http://localhost:8080/api/admin/stats; echo
200
401
Hello, asha [ROLE_STUDENT]
401
403
Total students: 1250
How it works:
- Rules are checked top to bottom, and the first match wins. Put specific paths first and finish with
anyRequest(). httpBasicreads theAuthorization: Basic ...header thatcurl -usends. Asha has noADMINrole, so she gets 403 on/api/admin/stats; Ravi gets the data.roles("STUDENT")is stored as the authorityROLE_STUDENT.hasRole("ADMIN")adds theROLE_prefix for you./erroris public so that error responses (401, 403, 404) are not blocked by the security rules themselves.
Authorization Rules Reference
| Rule | Allows |
|---|---|
permitAll() | Everyone, logged in or not |
authenticated() | Any logged-in user |
hasRole("ADMIN") | Users with authority ROLE_ADMIN |
hasAnyRole("ADMIN", "TEACHER") | Users with at least one of the roles |
hasAuthority("course:write") | Users with that exact authority string |
denyAll() | Nobody |
You can also limit a rule to one HTTP method, for example .requestMatchers(HttpMethod.GET, "/api/courses/**").permitAll() lets anyone read courses while other methods still need a login.
Store Passwords With a PasswordEncoder
Never store plain passwords. A PasswordEncoder turns a password into a salted, slow hash and later checks login attempts against it, as explained in Java password hashing.
@Bean
CommandLineRunner encoderDemo(PasswordEncoder encoder) {
return args -> {
String stored = encoder.encode("asha-pass");
System.out.println("Stored value: " + stored);
System.out.println("Correct password? " + encoder.matches("asha-pass", stored));
System.out.println("Wrong password? " + encoder.matches("asha-pas", stored));
System.out.println("Same hash twice? " + stored.equals(encoder.encode("asha-pass")));
};
}
Stored value: {bcrypt}$2a$10$Yq0yK7c3mN9yH2bqvQe8me0b1lH3cQm4uJ1x7gq6r2kq8yYbqv5aW
Correct password? true
Wrong password? false
Same hash twice? false
How it works:
- The delegating encoder writes the algorithm id in braces before the hash. Later you can switch to a stronger default and old hashes still verify, because each one names its own algorithm.
- Every call to
encodeuses a new random salt, so the same password never produces the same stored value. That is why you compare withmatches, never withequals. - Your hash will differ from the one shown; only the
{bcrypt}prefix and thetrue/false/falselines stay the same.
Read the Logged-In User in a Controller
Controllers can receive the current user directly as a parameter.
@GetMapping("/api/profile")
public Map<String, Object> profile(@AuthenticationPrincipal UserDetails user, Authentication authentication) {
boolean isAdmin = user.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
return Map.of(
"username", authentication.getName(),
"admin", isAdmin);
}
curl -s -u ravi:ravi-pass http://localhost:8080/api/profile; echo
{"admin":true,"username":"ravi"}
How it works:
@AuthenticationPrincipalinjects theUserDetailsobject that theUserDetailsServiceloaded.Authenticationgives the same user in a more general form, withgetName()returning the username.- Outside a controller you can call
SecurityContextHolder.getContext().getAuthentication()to reach the same object. - The key order in the printed JSON may differ, because
Map.ofhas no fixed order.
Form Login and Logout for Web Pages
Browser apps built with Spring MVC usually use a login form and a session cookie instead of HTTP Basic.
@Bean
SecurityFilterChain webSecurity(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/courses/**", "/css/**", "/error").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin(form -> form
.defaultSuccessUrl("/dashboard", true)) // where to go after login
.logout(logout -> logout
.logoutSuccessUrl("/")); // where to go after logout
return http.build();
}
curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" http://localhost:8080/dashboard
302 http://localhost:8080/login
How it works:
- An anonymous browser request to a protected page is redirected to
/login. Spring Security generates a simple login page there until you provide your own template. - After a successful login the user ID is kept in the HTTP session, so the browser sends only the session cookie on later requests.
- CSRF protection stays on for form-based apps. Spring adds a hidden
_csrftoken to forms rendered with Thymeleaf, and POST, PUT and DELETE requests without a valid token get 403.
Method Security With @PreAuthorize
URL rules protect endpoints. Method security protects service methods, so the rule holds no matter which controller calls them.
package com.gocourse.secure;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}
package com.gocourse.secure;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class ReportService {
@PreAuthorize("hasRole('ADMIN')")
public String revenueReport() {
return "Revenue this month: INR 4,82,000";
}
// a student may read only their own progress; admins may read anyone's
@PreAuthorize("#username == authentication.name or hasRole('ADMIN')")
public String progressOf(String username) {
return username + " has finished 12 of 20 lessons";
}
}
@RestController
@RequestMapping("/api")
public class ReportController {
private final ReportService reports;
public ReportController(ReportService reports) {
this.reports = reports;
}
@GetMapping("/reports/revenue")
public String revenue() {
return reports.revenueReport();
}
@GetMapping("/progress/{username}")
public String progress(@PathVariable String username) {
return reports.progressOf(username);
}
}
curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass http://localhost:8080/api/reports/revenue
curl -s -u asha:asha-pass http://localhost:8080/api/progress/asha; echo
curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass http://localhost:8080/api/progress/ravi
curl -s -u ravi:ravi-pass http://localhost:8080/api/progress/asha; echo
403
asha has finished 12 of 20 lessons
403
asha has finished 12 of 20 lessons
How it works:
@EnableMethodSecuritywraps beans that use@PreAuthorizein a proxy. The expression is checked before the method runs; if it is false, anAccessDeniedExceptionbecomes a 403 response.#usernamerefers to the method parameter andauthentication.nameto the logged-in user, so the rule compares them.
Note:
#usernameworks because Spring Boot's Maven and Gradle setup compiles with the-parametersflag, which keeps parameter names in the class file.
Secure a Stateless REST API: CSRF and Sessions
A REST API called by mobile apps or scripts sends credentials (or a token) with every request and has no login form. For such an API you turn off sessions and CSRF.
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.POST, "/api/register").permitAll()
.requestMatchers("/api/public/**", "/error").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
| Setting | Browser app with login form | Stateless REST API |
|---|---|---|
| Login | formLogin | httpBasic or a bearer token |
| Session | Created after login | STATELESS, none |
| CSRF | Enabled | Disabled |
How it works:
- CSRF attacks trick a browser into sending its cookie to your site. A stateless API does not use cookies for login, so the attack has nothing to steal and the protection can be turned off.
STATELESSstops Spring Security from creating anHttpSession, so every request is authenticated on its own.
Note: Keep CSRF enabled whenever authentication travels in a cookie. Disabling it in a session-based web app opens a real security hole.
Real-World Example: Spring Security With Database Users
Real applications keep users in a database. This example stores them with Spring Data JPA, lets students register, blocks disabled accounts and gives admins a user list. It uses the stateless apiSecurity chain above (as the only SecurityFilterChain), the PasswordEncoder bean, and H2 as in the previous lesson.
package com.gocourse.secure.user;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 40)
private String username;
@Column(nullable = false)
private String password; // always a hash, never plain text
@Column(nullable = false)
private String role; // STUDENT or ADMIN
private boolean enabled = true;
protected AppUser() {}
public AppUser(String username, String passwordHash, String role, boolean enabled) {
this.username = username;
this.password = passwordHash;
this.role = role;
this.enabled = enabled;
}
public String getUsername() { return username; }
public String getPassword() { return password; }
public String getRole() { return role; }
public boolean isEnabled() { return enabled; }
}
package com.gocourse.secure.user;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AppUserRepository extends JpaRepository<AppUser, Long> {
Optional<AppUser> findByUsername(String username);
boolean existsByUsername(String username);
}
package com.gocourse.secure.user;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class UserConfig {
// Spring Security calls this on every login attempt
@Bean
UserDetailsService userDetailsService(AppUserRepository users) {
return username -> users.findByUsername(username)
.map(user -> User.withUsername(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.disabled(!user.isEnabled())
.build())
.orElseThrow(() -> new UsernameNotFoundException("No user " + username));
}
@Bean
CommandLineRunner seedUsers(AppUserRepository users, PasswordEncoder encoder) {
return args -> {
users.save(new AppUser("ravi", encoder.encode("ravi-pass"), "ADMIN", true));
users.save(new AppUser("old", encoder.encode("old-pass"), "STUDENT", false));
};
}
}
package com.gocourse.secure.user;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequestMapping("/api")
public class AccountController {
record RegisterRequest(String username, String password) {}
private final AppUserRepository users;
private final PasswordEncoder encoder;
public AccountController(AppUserRepository users, PasswordEncoder encoder) {
this.users = users;
this.encoder = encoder;
}
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public void register(@RequestBody RegisterRequest request) {
if (users.existsByUsername(request.username())) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Username taken");
}
users.save(new AppUser(request.username(), encoder.encode(request.password()), "STUDENT", true));
}
@GetMapping("/me")
public String me(@AuthenticationPrincipal UserDetails user) {
return "Hello, " + user.getUsername() + " " + user.getAuthorities();
}
@GetMapping("/admin/users")
public List<String> allUsers() {
return users.findAll(Sort.by("username")).stream()
.map(AppUser::getUsername)
.toList();
}
}
# register a new student (public endpoint)
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" \
-d '{"username":"meena","password":"meena-pass"}' http://localhost:8080/api/register
# same username again
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" \
-d '{"username":"meena","password":"other"}' http://localhost:8080/api/register
curl -s -u meena:meena-pass http://localhost:8080/api/me; echo
curl -s -o /dev/null -w "%{http_code}\n" -u old:old-pass http://localhost:8080/api/me
curl -s -o /dev/null -w "%{http_code}\n" -u meena:meena-pass http://localhost:8080/api/admin/users
curl -s -u ravi:ravi-pass http://localhost:8080/api/admin/users; echo
201
409
Hello, meena [ROLE_STUDENT]
401
403
["meena","old","ravi"]
How it works:
- Registration.
/api/registeris public for POST. The controller hashes the password with thePasswordEncoderbefore saving, so theapp_usertable never holds plain text. A duplicate username returns 409 Conflict. - Login on every request. Because the chain is stateless, each
curl -ucall runs theUserDetailsService, which loads the row by username. Spring Security then checks the password withencoder.matchesand the role rules. - Disabled accounts.
disabled(!user.isEnabled())makes Spring Security reject theoldaccount with 401 even though its password is correct. Admins can block a user by flipping one column instead of deleting the row. - Role checks. Meena is a
STUDENT, so/api/admin/usersreturns 403. Ravi hasADMINand gets the sorted user list. - Clear layering. Security rules live in the
SecurityFilterChain, user loading in theUserDetailsService, and business logic in the controller. Building a full REST API in Java on top of this only means adding controllers; the security setup stays the same.