401 vs 403 Errors in Spring Security
401 Unauthorized and 403 Forbidden are the two status codes Spring Security uses to say "no". They mean different things, and reading them correctly is the quickest way to fix a security problem: a 401 says "I do not know who you are", a 403 says "I know who you are, and the answer is still no".
Despite its name, 401 is about authentication, not authorization. This page compares the two, lists which Spring Security component returns each one, and reproduces every common cause against a small school portal so you can match your own error to a real example.
1. What Do 401 and 403 Mean?
401 Unauthorized (RFC 9110) means the request lacks valid authentication credentials for the resource. The server must include a WWW-Authenticate header naming the scheme the client should use, such as Basic or Bearer. Sending correct credentials may succeed.
403 Forbidden means the server understood the request and refuses to fulfil it. Authenticating again with the same account will not help. In Spring Security a 403 usually means a missing role or permission, or a failed protection check such as CSRF. The general concepts are explained in authentication vs authorization.
2. 401 vs 403: Key Differences
| Aspect | 401 Unauthorized | 403 Forbidden |
|---|---|---|
| Meaning | Not authenticated, or credentials invalid | Authenticated (or check failed), but not allowed |
| Concept | Authentication | Authorization or request protection |
| Required header | WWW-Authenticate | None |
| Will logging in help? | Yes, with valid credentials | No, not with the same account |
| Spring component | AuthenticationEntryPoint | AccessDeniedHandler |
| Typical exception | AuthenticationException, or access denied for an anonymous user | AccessDeniedException for a known user, InvalidCsrfTokenException |
| Browser apps with form login | Replaced by a 302 redirect to /login | Still 403 (or an error page) |
3. How Spring Security Chooses Between Them
The decision is made by ExceptionTranslationFilter and by the authentication filters themselves, as described in exception handling. One detail surprises people: when an anonymous user hits a rule such as hasRole("TEACHER"), the result is 401, not 403, because logging in might fix it.
4. Example: Every Common Cause on a School Portal
A school portal has an API under /api/** (HTTP Basic) and a browser portal under /portal/** (form login). Students read grades; teachers enter them. CSRF protection is left at its default on the API chain to show its effect. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.
package com.javabytechie.school;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
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.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
@Order(1)
SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**")
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/grades/entry").hasRole("TEACHER")
.requestMatchers(HttpMethod.POST, "/api/grades").hasRole("TEACHER")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults()); // CSRF stays at its default (on)
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain portalChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo accounts only
return new InMemoryUserDetailsManager(
User.withUsername("arya").password(encoder.encode("arya-pass")).roles("STUDENT").build(),
User.withUsername("kabir").password(encoder.encode("kabir-pass")).roles("STUDENT")
.accountLocked(true).build(),
User.withUsername("ms-rao").password(encoder.encode("rao-pass")).roles("TEACHER").build());
}
}
package com.javabytechie.school;
import java.security.Principal;
import java.util.List;
import java.util.Map;
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.RestController;
@RestController
public class GradeController {
@GetMapping("/api/grades")
public List<String> myGrades(Principal principal) {
return List.of(principal.getName() + ": Maths A, Physics B+");
}
@GetMapping("/api/grades/entry")
public String entryForm() {
return "Grade entry for class 10-B";
}
@PostMapping("/api/grades")
public Map<String, String> enter(@RequestBody Map<String, String> grade) {
return grade;
}
@GetMapping("/portal/timetable")
public String timetable() {
return "Mon: Maths, Physics, English";
}
}
package com.javabytechie.school;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SchoolPortalApplication {
public static void main(String[] args) {
SpringApplication.run(SchoolPortalApplication.class, args);
}
}
5. Expected Output
Each request below triggers a different cause. Response bodies are omitted except for the successful call:
$ curl localhost:8080/api/grades
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
$ curl -u arya:wrong-pass localhost:8080/api/grades
HTTP/1.1 401
$ curl -u kabir:kabir-pass localhost:8080/api/grades
HTTP/1.1 401
$ curl -u arya:arya-pass localhost:8080/api/grades
HTTP/1.1 200
["arya: Maths A, Physics B+"]
$ curl -u arya:arya-pass localhost:8080/api/grades/entry
HTTP/1.1 403
$ curl -u ms-rao:rao-pass -X POST localhost:8080/api/grades -H 'Content-Type: application/json' -d '{"student":"arya","grade":"A"}'
HTTP/1.1 403
$ curl localhost:8080/portal/timetable
HTTP/1.1 302
Location: http://localhost:8080/login
With DEBUG logging for Basic authentication, the server log shows the reason behind the two failed logins, in order:
BadCredentialsException: Bad credentials
LockedException: User account is locked
6. Causes and Fixes at a Glance
The table summarises the run above and adds causes from other tutorials in this series:
| Situation | Status | Fix |
|---|---|---|
| No credentials sent | 401 + WWW-Authenticate | Send credentials or a token |
| Wrong password | 401 | Correct the credentials |
| Account locked, disabled or expired | 401 | Unlock or re-enable the account; the client is not told why |
| Bearer token expired or with a bad signature | 401 + error="invalid_token" | Obtain a new token; check issuer and keys (resource server) |
| Logged in, missing role or authority | 403 | Grant the role, or fix a ROLE_ mismatch (role vs authority) |
| Valid token without the required scope | 403 + error="insufficient_scope" | Request the scope from the authorization server |
| State-changing request without a CSRF token | 403 | Send the token, or exclude a non-browser API chain (CSRF protection) |
| Origin not allowed by CORS | 403 "Invalid CORS request" | Add the origin to the CORS configuration (CORS) |
@PreAuthorize or other method rule denied | 403 | Check the expression and the user's authorities |
| Anonymous user in a form-login app | 302 to /login | Expected; use a separate API chain for JSON clients |
7. Reading the Results
- No credentials gives 401 with
WWW-Authenticate: Basic, inviting the client to log in. - Wrong password and locked account both give 401. The client cannot tell them apart; only the server log shows
BadCredentialsExceptionandLockedException. - A student on the teacher endpoint gets 403: the login worked, the role is missing.
- The teacher's POST also gets 403, although her role is correct. CSRF protection rejected the request because it carried no token. This is the most common "mysterious 403" in Spring Boot. For an API used only by scripts and apps, disable CSRF on that chain; for a browser front end, send the token.
- The anonymous portal request gets 302 to the login page instead of 401, because form login's entry point redirects.
8. A Quick Debugging Checklist
- Read the status and headers first. A 401 with
WWW-Authenticatepoints to credentials; a 403 points to rules or protections; a 302 to/loginpoints to a browser chain handling an API call. - Check which chain handled the request. With several
SecurityFilterChainbeans, a missingsecurityMatchersends API calls to the wrong chain. - Turn on DEBUG or TRACE logging for
org.springframework.securitybriefly. The log names the exception and the filter that rejected the request. - Compare authorities with rules. Print the authorities of the logged-in user and compare them, character by character, with the rule, including the
ROLE_prefix.
9. Common Mistakes and Best Practices
- Returning 403 for missing credentials. Clients then never try to log in. Use 401 with
WWW-Authenticate. - Returning 401 for a missing role. Clients may loop through the login again. Use 403.
- Disabling CSRF to fix every 403. First check whether the 403 is a CSRF failure (DEBUG logging for
org.springframework.security.web.csrfshows "Invalid CSRF token found") or an authorization rule. - Hiding the cause from yourself. Keep client messages generic, but log the exception type at DEBUG or in an audit log.
- Consider 404 for hidden resources. If revealing that a record exists is itself a leak, some APIs answer 404 instead of 403 for records the caller may not see.
10. Summary
- 401 means "not authenticated"; 403 means "authenticated, but not allowed" or a failed protection check.
- A 401 must carry
WWW-Authenticate; Spring Security's entry points add it. - Wrong passwords, unknown users and locked accounts all return the same 401.
- Missing roles, missing scopes, CSRF failures and CORS rejections return 403.
- Form-login applications redirect anonymous users to
/logininstead of returning 401.
11. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between 401 and 403 in Spring Security?
401 is returned when the request is not authenticated or the credentials are invalid. 403 is returned when the user is authenticated but lacks permission, or when a protection such as CSRF rejects the request.
Q2. Why do I get 403 for a POST request even though I am an admin?
Most likely the request has no CSRF token. Spring Security enables CSRF protection by default for unsafe methods. Send the token, or disable CSRF only for a stateless API used by non-browser clients.
Q3. Why do I get 401 instead of 403 when a role is missing?
Because the request was anonymous. Spring Security answers 401 for anonymous users even when the rule is role-based, since logging in could grant access.
Q4. Why does Spring Security redirect to /login instead of returning 401?
Form login uses LoginUrlAuthenticationEntryPoint, which redirects browsers to the login page. For APIs, use a separate filter chain with HTTP Basic, a bearer token or a custom entry point that returns 401.
Q5. Does a locked account return 401 or 403?
401. LockedException is an authentication failure, and the client receives the same response as for a wrong password.