Skip to content
javahacks.dev
Security

Fix Spring Security 401 Unauthorized Responses in APIs

Fix a 401 Unauthorized from Spring Security by checking credentials, the Authorization header format, token validation settings and filter order.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the Spring Security, Spring Boot, Apache Maven, OpenJDK and Spring logos.

A client calls your API and gets back 401 Unauthorized with an empty body. The code is right, the endpoint exists and the same call worked yesterday. Spring Security is a chain of filters, and a 401 means one of them decided the request has no valid identity. It does not say which one, or why, unless you ask. This post gives a method that finds the cause in minutes: turn on the logs that explain the decision, then work through the five causes in order of frequency. They are credentials that were never sent, credentials that are wrong (or the generated default user), a token that does not validate, a path that should have been public and a response format that hides what happened. Examples use Spring Boot 4 and Spring Security 7, in a service that is a resource server for JWTs.

Step 1: turn on the log

Spring Security logs its decisions at DEBUG and TRACE, silent by default. Switch on the security packages and repeat the failing request:

src/main/resources/application.yamlYAML
logging:
  level:
    org.springframework.security: DEBUG
    org.springframework.security.web.FilterChainProxy: TRACE
Shell
curl -i http://localhost:8080/orders/7
Text
HTTP/1.1 401
WWW-Authenticate: Bearer

In the application log the TRACE line from FilterChainProxy lists every filter the request passed through, in order, and a DEBUG line from the authentication filter says what it found:

Text
Securing GET /orders/7
Did not find a bearer token in the request
Failed to authenticate since the request did not contain a valid token

That one line is the answer in many cases. Learn to read the filter list too: if BearerTokenAuthenticationFilter is missing, the security configuration never enabled the resource server; if AuthorizationFilter appears before authentication happened, a custom ordering is wrong. Always remove these log levels after debugging; they are verbose and can print request details. The reference for the authentication architecture is the Spring Security authentication documentation.

A 401 is also easy to confuse with its neighbor. 401 means the caller is unknown; 403 means the caller is known and not allowed to do this. A request that is authenticated and refused gets 403, with its own causes, in fixing 403 Forbidden on POST requests.

Cause 1: no credentials sent

The most common reason is the plainest: the request did not carry the header. The log says Did not find a bearer token or, for basic auth, shows an anonymous user. Check what the client really sent, not what it meant to send:

Shell
curl -v -H "Authorization: Bearer $TOKEN" http://localhost:8080/orders/7 2>&1 | grep -i '^> '
Text
> GET /orders/7 HTTP/1.1
> Host: localhost:8080
> Authorization: Bearer eyJhbGciOi...

Look for these specific slips. The variable $TOKEN was empty, so the header is Bearer with nothing after it. The scheme is wrong (Token abc or bearer spelled differently from what the server accepts; the match is case-insensitive for Bearer). A proxy or API gateway dropped the Authorization header, which some do for security by default. A browser client sent a cross-origin request and the preflight OPTIONS call, which carries no credentials, got a 401: allow OPTIONS through the security filter and configure CORS, as the preflight must succeed before the real request is sent. A redirect between http and https loses the header, because clients strip credentials on a redirect to another origin.

java
http.cors(Customizer.withDefaults())
    .authorizeHttpRequests(a -> a
        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .anyRequest().authenticated());

Cause 2: wrong credentials, or the default user

With HTTP Basic or form login, a wrong username or password gives 401 and the log shows Failed to authenticate since the password does not match stored value or Bad credentials. Spring Boot adds a trap here: with Spring Security on the classpath and no user configured, it creates a user named user with a random password printed at startup:

Text
Using generated security password: 8e557245-73e2-4286-969b-cd8b5e8e3c6a

If you called an endpoint with credentials you thought were configured, but your configuration never took effect, only that generated password works. Check that your UserDetailsService or SecurityFilterChain bean is actually picked up: a missing @Configuration, a component not under the scanned package or a second filter chain with a higher precedence. When you do configure users, stored passwords must be encoded, and a missing encoder produces a different failure, There is no PasswordEncoder mapped for the id "null":

java
@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

A stored password that looks like {noop}change-me or {bcrypt}$2a$... is the delegating encoder's format, with the id in braces telling it which algorithm to use. Do not hard-code credentials outside tests.

Cause 3: the JWT does not validate

For a resource server, a token is present and still rejected. The WWW-Authenticate header often says why, once you read past the first word:

Shell
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/orders/7
Text
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="Jwt expired at 2026-11-06T09:30:00Z", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

The error_description is the validator's reason. The ones you will meet:

DescriptionMeaningFix
Jwt expired at ...exp is in the pastGet a new token; check clock skew between servers
An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signatureSigned by a different key than the server trustsPoint issuer-uri or jwk-set-uri at the right issuer
The iss claim is not validToken's issuer differs from the configured oneAlign issuer-uri with the token's iss exactly, including a trailing slash
The aud claim is not validA custom audience validator rejected itRequest a token for this API's audience
Couldn't retrieve remote JWK setThe server could not reach the key endpointNetwork, DNS or proxy from the API to the identity provider

The last row is a startup or first-request failure that looks like an auth problem: the resource server fetches the issuer's keys over the network, and a certificate error on that call (PKIX path building failed) breaks every request; the fix is in PKIX path building failed. Decode the token to compare its claims with the configuration; the payload is plain base64url:

Shell
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{iss, aud, exp, scope}'
JSON
{
  "iss": "https://id.example.test/realms/shop",
  "aud": "shop-api",
  "exp": 1793957400,
  "scope": "orders.read"
}

Compare iss with the configured spring.security.oauth2.resourceserver.jwt.issuer-uri, and exp with date +%s. The validation rules and a safe setup are covered in validating JWTs safely in Java, and the reference is the JWT resource server documentation.

Cause 4: the path should be public

Some endpoints must work without credentials: the health check, the login endpoint, the OpenAPI document, static assets. By default Spring Security protects everything, and a missing rule returns 401 for them.

src/main/java/dev/javahacks/security/SecurityConfig.javajava
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests(a -> a
                    .requestMatchers("/actuator/health/**", "/v3/api-docs/**").permitAll()
                    .requestMatchers("/orders/**").authenticated()
                    .anyRequest().denyAll())
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
            .build();
}

Matchers are evaluated in order and the first match wins, so a broad rule above a narrow one makes the narrow one dead code. Be careful with permitAll() on a path that the error handler uses: when an exception occurs, Spring Boot forwards to /error, and if /error requires authentication, a 500 or 404 is turned into a 401 that hides the real problem. Add /error to the public list, or you will chase the wrong status code. A context path or servlet prefix also changes the matched path, so check what the log says it secured (Securing GET /api/orders/7) against your pattern.

Cause 5: the response format for APIs

Sometimes the 401 is correct and the client cannot tell why. By default a failed bearer authentication returns an empty body and a WWW-Authenticate header. A browser form-login setup redirects to a login page instead, which an API client sees as a 302 and then a login HTML page, not a 401. For an API, return a consistent JSON problem body and a proper challenge:

java
.exceptionHandling(e -> e.authenticationEntryPoint((request, response, ex) -> {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setContentType("application/problem+json");
    response.getWriter().write("""
        {"type":"about:blank","title":"Unauthorized","status":401,"detail":"Missing or invalid credentials"}
        """);
}))

Keep the detail generic: do not tell a caller whether the username exists or which claim failed, since that helps an attacker; log the specific reason server-side. If you mix a session-based web UI and a token API in one application, use two filter chains with different securityMatcher ranges so each gets the right entry point. The overall setup of a service with security from the start is in Spring Boot from first project to production.

Where this does not apply

If the response is 401 but never reaches your application, the gateway, ingress or CDN in front rejected it; check its logs, and compare curl straight to the pod. If the status is 403, the identity is established and the authorization rule refused it. And if the service is not Spring Security at all (a servlet filter you wrote, or a framework such as Quarkus), the log levels above do not apply, though the five causes do: no credentials, wrong credentials, a token that fails validation, a path that is not public and an opaque response.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.