Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Authentication Mechanisms

HTTP Basic and Stateless Authentication

Learn how HTTP Basic works, configure it in Spring Security, make an API stateless with SessionCreationPolicy.STATELESS, and know when Basic is and is not safe.

HTTP Basic is the simplest authentication scheme there is: every request carries the username and password in an Authorization header. It has no login page, no cookie and no session, which makes it popular for service-to-service calls, simple scripts and internal tools. It also has sharp edges. This lesson shows how it works on the wire, how to enable it, how to make an API truly stateless, and when to choose something else.

Real Spring code is shown read-only; the runnable parts are Java stand-ins for the header parsing and the stateless flow.

What the header looks like

The client joins the two values with a colon, encodes the result as Base64 and sends:

Text
Authorization: Basic YWxpY2U6cHctYWxpY2U=

Base64 is an encoding, not encryption: anyone who sees the header can read the password. Basic is therefore acceptable only over HTTPS. If the server has no valid credentials it answers 401 with WWW-Authenticate: Basic realm="Orders" and a browser pops up its own login dialog.

Java Encoding and decoding a Basic header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Splitting at the first colon matters: a username cannot contain one, but a password can. BasicAuthenticationConverter in Spring does the same thing.

Enabling it

Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(a -> a
            .requestMatchers("/health").permitAll()
            .anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults())
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .csrf(csrf -> csrf.disable());
    return http.build();
}

httpBasic adds BasicAuthenticationFilter. It reads the header, builds a UsernamePasswordAuthenticationToken, asks the AuthenticationManager, and on success stores the result in the SecurityContext for the rest of the request. On a missing or bad header it calls the BasicAuthenticationEntryPoint (the 401 with the challenge). To get JSON or no browser dialog, set a custom entry point (see exception handling); HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED) omits the WWW-Authenticate header, which stops the browser dialog.

What "stateless" means

SessionCreationPolicy.STATELESS tells Spring Security never to create or use an HttpSession to store the SecurityContext. Every request must carry its own proof. The server remembers nothing between requests, so:

  • any server instance can answer any request (easy horizontal scaling and no sticky sessions);
  • there is no session to hijack and no logout state;
  • the credentials are checked on every request, which has a cost: with Basic that is a password hash verification each time.

That last point is crucial. BCrypt deliberately takes tens of milliseconds, so a busy API with Basic spends most of its CPU hashing. Two common mitigations: cache the authenticated result briefly (a few seconds, keyed by a hash of the header), or replace Basic with API keys or tokens for the high-volume paths, where verification is a cheap hash or signature check.

The stand-in below shows both costs: a stateless server that verifies the password on every call, and the work counter that tells you what it costs.

Java Stateless: every request is verified (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line shows a real weakness of a naive implementation: unknown users return faster than known ones, so an attacker can learn which usernames exist. Spring's DaoAuthenticationProvider closes that gap by hashing a dummy password when the user is not found.

Basic versus session versus token

HTTP Basic Session (form login) Bearer token (JWT/opaque)
Credential sent each request Password Session id cookie Token
Server state None Session store None (JWT) or token store
Password exposure Every request Only at login Only when getting a token
Browser friendly Native dialog, poor UX Yes Needs JavaScript
Good for Scripts, internal tools, bootstrap Server-rendered sites SPAs, mobile apps, APIs

Basic with a long random API secret instead of a human password is a legitimate pattern (the username is the key id, the "password" is the secret). It is the model that many payment and cloud APIs use. The cost problem disappears if you verify that secret with a fast hash, because a 32-byte random value does not need a slow hash.

Pitfalls

  • No TLS. Basic over plain HTTP exposes the password to anyone on the path.
  • Credentials in URLs (https://user:pass@host/). They end up in logs and history. Use the header.
  • Browser caching of the dialog. A browser keeps sending the credentials for the realm until it is closed, and there is no real logout for Basic.
  • CSRF confusion. Browsers attach Basic credentials automatically once the user entered them, so a stateless API consumed by browsers is still open to CSRF unless you rely on headers the attacker cannot set. Pure API clients (no browser) can disable CSRF safely. See CSRF protection.
  • Mixing with sessions. If STATELESS is not set, Basic requests may still create sessions through other features. Set the policy explicitly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Authorization header of HTTP Basic contain?

    Base64 is an encoding, not protection, so Basic requires HTTPS.
  2. 2. What does SessionCreationPolicy.STATELESS do?

    Each request must carry its own credentials; nothing is remembered between requests.
  3. 3. Why can Basic be expensive for a busy API using BCrypt?

    Without a session or token, each call performs a deliberately slow password check.
  4. 4. Why split the decoded value at the first colon only?

    Everything after the first colon belongs to the password.
  5. 5. Which statement about Basic over HTTP (no TLS) is true?

    Base64 is trivially reversible, so TLS is mandatory.

Summary

  • Basic sends username:password (Base64) in every request; use it only over HTTPS.
  • httpBasic() adds BasicAuthenticationFilter; failures call the Basic entry point (401 plus WWW-Authenticate).
  • STATELESS means no session: scalable, but credentials are verified on every request.
  • Prefer tokens or API keys for high-volume or browser-facing APIs; Basic with random secrets is fine for service clients.
  • Set the session policy explicitly and decide CSRF based on whether browsers use the API.

Next: UserDetailsService and users