Sub topic 2
Bearer tokens on the wire
This chapter assumes you know basic HTTP (methods, headers, status codes) and can read a Spring Boot controller. It also assumes you have met the four OAuth2 roles from the previous chapter. Here you look at what the client actually sends to a resource server, how the server finds the token in a request, and what it sends back when the token is missing or rejected. Nothing here depends on whether the token is a JWT, so the chapter also applies to the opaque tokens covered later.
What "bearer" means
A bearer token is a credential that works for whoever holds it. The resource server does not ask the caller to prove it is the client the token was issued to. It only checks that the token is valid. This is the same property as a hotel key card: anyone who picks it up can open the door.
This has two consequences you will return to throughout the tutorial:
- Anyone who copies a token can use it until it expires or is revoked.
- The token must only travel over TLS, and it should not appear in logs, URLs, or browser history.
OAuth2 defines other token types, such as sender-constrained tokens bound to a client certificate (mTLS) or a proof-of-possession key (DPoP). This tutorial covers plain bearer tokens, which is what Spring Security's resource server support handles by default.
The Authorization header
RFC 6750 defines how bearer tokens are presented. The preferred method is the Authorization request header with the scheme Bearer, one space, and then the token:
GET /orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSJ9.c2lnbmF0dXJl
Accept: application/jsonA few details matter in practice:
- The scheme name is case-insensitive per HTTP, and Spring Security's default resolver accepts
bearer,Bearer, andBEARER. - The token must use only the characters
A-Z a-z 0-9 - . _ ~ + /, optionally followed by=padding. A JWT fits this because it is three Base64URL segments joined by dots. A token with spaces or quotes is rejected as malformed before any signature check happens. Authorization: Basic ...is a different scheme. A resource server configured for bearer tokens ignores it, and the request is treated as having no token.
The next example is a complete Java client that sends the header. It reads the token from an environment variable so no secret ends up in source code. It also prints the WWW-Authenticate response header, which matters later in this chapter.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class OrdersClient {
public static void main(String[] args) throws Exception {
String token = System.getenv("ACCESS_TOKEN");
if (token == null || token.isBlank()) {
throw new IllegalStateException("Set ACCESS_TOKEN first");
}
HttpRequest request = HttpRequest
.newBuilder(URI.create("http://localhost:8080/orders"))
.header("Authorization", "Bearer " + token)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
response.headers().firstValue("WWW-Authenticate")
.ifPresent(h -> System.out.println("Challenge: " + h));
System.out.println(response.body());
}
}Two other ways to send a token, and why to avoid them
RFC 6750 also describes sending the token as a form-encoded body parameter (access_token=... in a POST with application/x-www-form-urlencoded) and as a URI query parameter (/orders?access_token=...).
Spring Security supports both but turns both off by default. The query parameter is the dangerous one. URLs are written to web server access logs, proxy logs, browser history, and Referer headers, so the token leaks to places that were never meant to hold credentials. The form body method is safer but rarely needed.
The component that extracts the token is BearerTokenResolver. The default implementation is DefaultBearerTokenResolver. You only need to declare your own bean to change its behavior. This example makes the defaults explicit:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
@Configuration
public class BearerTokenConfig {
@Bean
BearerTokenResolver bearerTokenResolver() {
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowUriQueryParameter(false); // default
resolver.setAllowFormEncodedBodyParameter(false); // default
return resolver;
}
}DefaultBearerTokenResolver also has setBearerTokenHeaderName(String), for the rare case where a gateway forwards the token in a header other than Authorization.
If a request carries a token in more than one place, for example both a header and a query parameter, the default resolver treats it as ambiguous and rejects it with an invalid_request error. This follows RFC 6750, which forbids using more than one method per request.
Where the token is read in the Spring Security filter chain
When you enable oauth2ResourceServer(...) in the next chapters, Spring Security adds a BearerTokenAuthenticationFilter. For each request it does the following:
- It asks the
BearerTokenResolverfor a token string. - If there is no token, it does nothing and passes the request along. The request stays anonymous.
- If there is a token, it wraps the string in a
BearerTokenAuthenticationToken, which is not yet authenticated, and hands it to theAuthenticationManager. - A provider validates the token. For JWTs this is the
JwtAuthenticationProviderand aJwtDecoder. For opaque tokens it is an introspection provider. - On success, the resulting authenticated
Authenticationis stored in theSecurityContext. On failure, theAuthenticationEntryPointproduces a 401 response.
Step 2 explains a point that confuses many developers. A request with no token is not rejected by this filter. It is rejected later by the authorization rules (anyRequest().authenticated()), and the response comes from the entry point. A request to a permitAll() path with no token succeeds. A request to a permitAll() path with an invalid token fails with 401, because the filter runs first and validates any token it finds.
What the server sends back: the WWW-Authenticate challenge
HTTP says that a 401 response must include a WWW-Authenticate header telling the client which scheme to use. For bearer tokens, RFC 6750 defines the content. Spring Security follows it:
| Situation | Status | WWW-Authenticate value |
|---|---|---|
| No token sent | 401 | `Bearer` |
| Malformed request, such as two tokens | 401 | `Bearer error="invalid_request"` |
| Token expired, bad signature, wrong issuer | 401 | `Bearer error="invalid_token", error_description="..."` |
| Valid token, missing permission | 403 | `Bearer error="insufficient_scope"` |
The exact attributes vary with the Spring Security version and with the failure. Treat the table as the shape of the response, and check your own application's output when you write client code.
Notice the first row. A missing token produces only the bare scheme with no error attribute. RFC 6750 says that a request lacking any authentication information should not carry an error code, because the client did nothing wrong in the protocol sense. It simply has not authenticated yet.
Clients should use this header, not the response body, to decide what to do. A 401 with invalid_token and an expiry description usually means "get a new access token, using your refresh token or by logging in again, and retry". A 403 means a new token with the same scopes will not help.
Practical rules for working with bearer tokens
- Send tokens only in the
Authorizationheader and only over HTTPS. - Never log the full header value. If you log requests, mask the part after
Bearer. - Make the client treat the token as an opaque string. Even when it is a JWT, a client application should not depend on reading its contents. Only the resource server is meant to interpret it.
- Reject anything else at the edge. If a gateway terminates TLS and forwards requests, make sure it forwards the
Authorizationheader unchanged. - Remember that CORS preflight (
OPTIONS) requests do not carry the header. This is covered in the pitfalls chapter.
Exercise
A request to a path declared with permitAll() carries an Authorization header whose token has expired. What status does the resource server return, and why? What would it return if the same request had no Authorization header at all?
Show answer
With the expired token it returns 401, with a WWW-Authenticate header whose value includes error="invalid_token". BearerTokenAuthenticationFilter runs before authorization rules are evaluated. It finds a token, tries to authenticate it, and fails, so the authentication entry point answers before permitAll() is considered. With no Authorization header, the filter finds no token and passes the request on as anonymous. permitAll() then allows it, and the request succeeds, typically with 200.
Exercise
Why does Spring Security disable the access_token query parameter by default, and which component would you configure to change that?
Show answer
URLs are recorded in server and proxy logs, browser history, and Referer headers, so a token in a URL leaks into places that are not protected like credentials. The behavior is controlled by the BearerTokenResolver, specifically DefaultBearerTokenResolver.setAllowUriQueryParameter(boolean), which you set by declaring your own BearerTokenResolver bean.