00:00

401 vs 403 Errors in Spring Security

Last updated:

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

Aspect401 Unauthorized403 Forbidden
MeaningNot authenticated, or credentials invalidAuthenticated (or check failed), but not allowed
ConceptAuthenticationAuthorization or request protection
Required headerWWW-AuthenticateNone
Will logging in help?Yes, with valid credentialsNo, not with the same account
Spring componentAuthenticationEntryPointAccessDeniedHandler
Typical exceptionAuthenticationException, or access denied for an anonymous userAccessDeniedException for a known user, InvalidCsrfTokenException
Browser apps with form loginReplaced by a 302 redirect to /loginStill 403 (or an error page)

3. How Spring Security Chooses Between Them

Decision between 401 and 403If credentials are missing or invalid, the authentication entry point returns 401 (or a login redirect). If the user is authenticated but lacks permission, or a CSRF check fails, the access denied handler returns 403. Request rejected Caller unknown or credentials bad? anonymous, wrong password, bad token Caller known, or protection failed? missing role, CSRF, method rule 401 Unauthorized AuthenticationEntryPoint 403 Forbidden AccessDeniedHandler
Figure 1: unknown caller: 401 through the entry point; known caller without permission, or a failed protection check: 403.

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());
    }
}

5. Expected Output

Each request below triggers a different cause. Response bodies are omitted except for the successful call:

Terminal
$ 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:

Terminal
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:

SituationStatusFix
No credentials sent401 + WWW-AuthenticateSend credentials or a token
Wrong password401Correct the credentials
Account locked, disabled or expired401Unlock or re-enable the account; the client is not told why
Bearer token expired or with a bad signature401 + error="invalid_token"Obtain a new token; check issuer and keys (resource server)
Logged in, missing role or authority403Grant the role, or fix a ROLE_ mismatch (role vs authority)
Valid token without the required scope403 + error="insufficient_scope"Request the scope from the authorization server
State-changing request without a CSRF token403Send the token, or exclude a non-browser API chain (CSRF protection)
Origin not allowed by CORS403 "Invalid CORS request"Add the origin to the CORS configuration (CORS)
@PreAuthorize or other method rule denied403Check the expression and the user's authorities
Anonymous user in a form-login app302 to /loginExpected; use a separate API chain for JSON clients

7. Reading the Results

  1. No credentials gives 401 with WWW-Authenticate: Basic, inviting the client to log in.
  2. Wrong password and locked account both give 401. The client cannot tell them apart; only the server log shows BadCredentialsException and LockedException.
  3. A student on the teacher endpoint gets 403: the login worked, the role is missing.
  4. 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.
  5. 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

  1. Read the status and headers first. A 401 with WWW-Authenticate points to credentials; a 403 points to rules or protections; a 302 to /login points to a browser chain handling an API call.
  2. Check which chain handled the request. With several SecurityFilterChain beans, a missing securityMatcher sends API calls to the wrong chain.
  3. Turn on DEBUG or TRACE logging for org.springframework.security briefly. The log names the exception and the filter that rejected the request.
  4. 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.csrf shows "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 /login instead of returning 401.

11. References