Skip to lesson

HTTP Basic authentication

A mobile app must show a customer their ShopLite orders, so the server must know who is asking on every call. The simplest answer is to attach the email and password to each request. What does it cost?

The Authorization: Basic header

HTTP Basic is a sign-in method where the client sends Authorization: Basic followed by the Base64 of username:password on every request. For ShopLite the user name is the email.

The next program builds Asha's header by hand and then decodes it again, exactly as anyone who sees the header could.

Example 1 · Build and decode a Basic header by hand

BasicHeaderDemo.javaJava
import java.nio.charset.StandardCharsets;import java.util.Base64;
public class BasicHeaderDemo {
    static String basicHeader(String email, String password) {        String pair = email + ":" + password;        byte[] bytes = pair.getBytes(StandardCharsets.UTF_8);        return "Basic " + Base64.getEncoder().encodeToString(bytes);    }
    public static void main(String[] args) {        String header = basicHeader("asha.rao@example.com", "Mango#2026");        System.out.println("Authorization: " + header);
        // What anyone who sees the header can do: no key needed        String encoded = header.substring("Basic ".length());        String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);        System.out.println("Decoded: " + decoded);
        // The server splits at the FIRST colon: a password may contain ':', an email may not        int colon = decoded.indexOf(':');        System.out.println("Username: " + decoded.substring(0, colon));        System.out.println("Password: " + decoded.substring(colon + 1));
        String tricky = basicHeader("ravi.kumar@example.com", "shop:time:42");        String back = new String(Base64.getDecoder().decode(tricky.substring(6)), StandardCharsets.UTF_8);        int first = back.indexOf(':');        System.out.println("Ravi's password: " + back.substring(first + 1));    }}
Output
Authorization: Basic YXNoYS5yYW9AZXhhbXBsZS5jb206TWFuZ28jMjAyNg==
Decoded: asha.rao@example.com:Mango#2026
Username: asha.rao@example.com
Password: Mango#2026
Ravi's password: shop:time:42

What this code does

  • basicHeader joins email and password with a colon, turns the text into UTF-8 bytes and Base64-encodes them: this is all curl -u does.
  • Decoding needs no key or secret. The header in Example 3's curl -v output is exactly this value, so anyone who sees it has Asha's password.
  • Ravi's password shop:time:42 survives because the split happens at the first colon only.

Base64 is encoding, not encryption (the Security basics module showed the difference): it only turns bytes into safe text, so the header can be decoded with no key. The server splits the decoded text at the first colon, which is why a password may contain a colon and a user name may not. Spring reads the bytes as UTF-8 by default, and its 401 reply says so with charset="UTF-8".

Predict the output

Read a Basic header

Pick what each header gives away. Nothing runs: reason from what you just saw.

Round 1 of 2

Someone copies this header from a log file. What can they read from it?

GET /api/v1/me HTTP/1.1
Authorization: Basic YXNoYS5yYW9AZXhhbXBsZS5jb206TWFuZ28jMjAyNg==
Basic is only as safe as the connection. Over plain HTTP the header is readable by every router on the way; over HTTPS it is encrypted in transit.

httpBasic(Customizer.withDefaults()) and curl -u

BasicAuthenticationFilter is the Spring Security filter that reads the Authorization: Basic header, asks the AuthenticationManager to check it and stops the request with 401 when the check fails. httpBasic(Customizer.withDefaults()) adds it to the filter chain.

One line, httpBasic(Customizer.withDefaults()), turns Basic on. The lab keeps two users in memory so it runs without MySQL; ShopLite checks its app_user table instead.

Example 2 · SecurityConfig.java and LabUsers.java

Runs in: the basic-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
// src/main/java/com/shoplite/lab/security/SecurityConfig.javapackage com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;
@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll()                .requestMatchers("/error").permitAll()                .anyRequest().authenticated())            .httpBasic(Customizer.withDefaults())          // read the Authorization: Basic header            .csrf(csrf -> csrf.disable())            .sessionManagement(session -> session                .sessionCreationPolicy(SessionCreationPolicy.STATELESS));        return http.build();    }}
// src/main/java/com/shoplite/lab/security/LabUsers.javapackage com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.core.userdetails.User;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/** LAB ONLY: two users kept in memory so the lab runs without a database. */@Configurationclass LabUsers {
    @Bean    PasswordEncoder passwordEncoder() {        return new BCryptPasswordEncoder();    }
    @Bean    InMemoryUserDetailsManager users(PasswordEncoder encoder) {        return new InMemoryUserDetailsManager(                User.withUsername("asha.rao@example.com")                        .password(encoder.encode("Mango#2026")).roles("CUSTOMER").build(),                User.withUsername("admin@shoplite.example")                        .password(encoder.encode("Admin#Lab2026")).roles("ADMIN").build());    }}
Output
$ curl -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

$ curl -u 'admin@shoplite.example:Admin#Lab2026' http://localhost:8080/api/v1/me
{"email":"admin@shoplite.example","authorities":["ROLE_ADMIN","FACTOR_PASSWORD"]}

$ curl http://localhost:8080/api/v1/products
[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00},{"id":9,"sku":"BK-CLEAN","name":"Clean Code","price":499.00}]

What this code does

  • httpBasic(Customizer.withDefaults()) is the line that turns Basic on. The csrf and STATELESS lines are explained in the CSRF and stateless lessons of this module; for an API that only reads the Authorization header they are the right settings.
  • LabUsers stores BCrypt hashes made at startup with the PasswordEncoder bean. Only the lab does this; ShopLite reads users and hashes from MySQL.
  • Products are public, so curl without -u works there, while /api/v1/me needs a signed-in user.

Example 3 · curl -u, a wrong password and the header on the wire

Runs in: the basic-lab practice project (Spring Boot 4.1)

Terminal
curl -i -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/mecurl -i -u 'asha.rao@example.com:wrong' http://localhost:8080/api/v1/mecurl http://localhost:8080/api/v1/productscurl -v -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
Sample output
$ curl -i -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Content-Length: 82
Date: Fri, 16 Oct 2026 07:07:42 GMT

{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

$ curl -i -u 'asha.rao@example.com:wrong' http://localhost:8080/api/v1/me
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:07:42 GMT

{"timestamp":"2026-10-16T07:07:42.309Z","status":401,"error":"Unauthorized","path":"/api/v1/me"}

$ curl http://localhost:8080/api/v1/products
[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00},{"id":9,"sku":"BK-CLEAN","name":"Clean Code","price":499.00}]

$ curl -v -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
* Host localhost:8080 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
*   Trying [::1]:8080...
* Connected to localhost (::1) port 8080
* Server auth using Basic with user 'asha.rao@example.com'
> GET /api/v1/me HTTP/1.1
> Host: localhost:8080
> Authorization: Basic YXNoYS5yYW9AZXhhbXBsZS5jb206TWFuZ28jMjAyNg==
> User-Agent: curl/8.8.0
> Accept: */*
>
* Request completely sent off
< HTTP/1.1 200
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/json
< Content-Length: 82
< Date: Fri, 16 Oct 2026 07:07:42 GMT
<
{ [82 bytes data]
* Connection #0 to host localhost left intact
{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

What this code does

  • A right password gives 200 and the user's email and authorities; a wrong one gives 401 with WWW-Authenticate, and the controller never runs.
  • In the -v output, lines starting with > are what curl sent: Authorization: Basic YXNoYS5yYW9A... is the same text Example 1 printed.
  • The extra headers such as X-Frame-Options: DENY and Cache-Control: no-store are added by Spring Security to every response.

Behind the manager, the UserDetailsService loads the user and the PasswordEncoder compares the password with the stored BCrypt hash, exactly as in the previous module. A pass puts the user in the SecurityContext for this request only, so the next request must send the header again; a fail ends with 401 Unauthorized before the controller runs. On the command line, curl -u email:password builds the header, and single quotes keep characters such as #, & or ! away from the shell.

Spring Security 7 adds the authority FACTOR_PASSWORD next to the roles. The extra authority records how the user proved who they are (with a password), and multi-factor sign-in builds on it. Role checks use the ROLE_ authorities and can ignore it.

WWW-Authenticate and the browser pop-up

WWW-Authenticate is the response header on a 401 that names the sign-in scheme the server expects, for example Basic realm="ShopLite". The realm is just a label for the protected area.

A request with no header gets a 401, and WWW-Authenticate tells the client what to send next. The picture shows the whole round trip.

HTTP Basic round trip. The client sends GET /api/v1/me with no Authorization header. The server answers 401 Unauthorized with WWW-Authenticate: Basic. The client sends the same GET again with Authorization: Basic followed by the Base64 of email and password.

Example 4 · The 401 reply and a custom realm

Runs in: the basic-lab practice project (Spring Boot 4.1)

Terminal
curl -i http://localhost:8080/api/v1/me
Sample output
$ curl -i http://localhost:8080/api/v1/me
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:07:41 GMT

{"timestamp":"2026-10-16T07:07:41.213Z","status":401,"error":"Unauthorized","path":"/api/v1/me"}

(after changing the line to .httpBasic(basic -> basic.realmName("ShopLite")) and restarting)

$ curl -i http://localhost:8080/api/v1/me
HTTP/1.1 401
WWW-Authenticate: Basic realm="ShopLite", charset="UTF-8"
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:10:29 GMT

{"timestamp":"2026-10-16T07:10:29.622Z","status":401,"error":"Unauthorized","path":"/api/v1/me"}

What this code does

  • With no header at all, Spring answers 401 and asks for Basic. A browser would now show its pop-up with the realm name in it.
  • After .httpBasic(basic -> basic.realmName("ShopLite")) only the realm text changes; the status and body stay the same.

A browser that receives this header shows its own small sign-in pop-up, which you cannot style and which has no "forgot password" link. After a correct entry the browser remembers the email and password and adds them to every later request to that site until it is closed. basic.realmName("ShopLite") changes the realm text.

The pop-up is a problem for a web page that calls the API with JavaScript: a failed call suddenly opens a browser dialog. Browsers show it only for Basic (and a few older schemes), so the token login in the JWT module, which answers with WWW-Authenticate: Bearer, never triggers it.

Order of execution

Put the Basic round trip in order

Arrange the steps from the first request to the answer.

The JSON body of the 401 is Spring Boot's default error body. A later module makes every 401 a ShopLite problem response with the type unauthorized.

Weaknesses: password on every request, no logout, no expiry

Logout is the test of any sign-in method. The next commands call /logout and then use the same header again.

Example 5 · Logout does not stop a Basic header

Runs in: the basic-lab practice project (Spring Boot 4.1)

Terminal
curl -i -X POST -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/logoutcurl -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/mecurl -H 'Authorization: Basic YXNoYS5yYW9AZXhhbXBsZS5jb206TWFuZ28jMjAyNg==' http://localhost:8080/api/v1/me
Sample output
$ curl -i -X POST -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/logout
HTTP/1.1 204
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Date: Fri, 16 Oct 2026 07:10:28 GMT

$ curl -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

$ curl -H 'Authorization: Basic YXNoYS5yYW9AZXhhbXBsZS5jb206TWFuZ28jMjAyNg==' http://localhost:8080/api/v1/me
{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

What this code does

  • Spring Security adds a /logout endpoint by default, and it answers 204. But there is no session to end: the server never stored anything about Asha.
  • The very next request with the same header, typed by Asha or copied from a log by someone else, is accepted. Only a password change stops it.

Basic's biggest weakness is that the real password travels with every request. A login form sends it once; Basic sends it a hundred times while a customer browses orders, and each copy can end up in a proxy log, a debug print of the headers, a browser extension or a screenshot.

There is no logout and no expiry: the header is valid as long as the password is, and the only way to cut off a leaked header is to change the password, which also locks out every honest app using it. A good password hash is slow on purpose, so the server also pays a BCrypt check (tens of milliseconds) on every request, and every endpoint becomes a place to guess passwords.

Find the bug

Find the line that leaks the login

Click the line that puts a Basic login at risk.

A developer adds logging to debug a 401. Which line leaks a login?

Round 1 of 2

Where Basic is still fine: internal tools and service-to-service calls

Some callers are programs, not people. Here an order service calls a stock service with a long random secret, on a local test server.

Example 6 · Service-to-service call with a Basic secret

ServiceToServiceDemo.javaJava
import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;
/** A tiny "stock service" that only the order service may call. */class StockService {
    private static final byte[] EXPECTED =            "order-service:s3cret-from-env".getBytes(StandardCharsets.UTF_8);
    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);        server.createContext("/internal/stock/MOB-RN13", StockService::handle);        server.start();        return server;    }
    private static void handle(HttpExchange exchange) throws IOException {        String header = exchange.getRequestHeaders().getFirst("Authorization");        if (!isAllowed(header)) {            exchange.getResponseHeaders().add("WWW-Authenticate", "Basic realm=\"stock\"");            send(exchange, 401, "{\"error\":\"unauthorized\"}");            return;        }        send(exchange, 200, "{\"sku\":\"MOB-RN13\",\"stock\":40}");    }
    private static boolean isAllowed(String header) {        if (header == null || !header.startsWith("Basic ")) {            return false;        }        byte[] given;        try {            given = Base64.getDecoder().decode(header.substring(6));        } catch (IllegalArgumentException notBase64) {            return false;        }        return MessageDigest.isEqual(given, EXPECTED);   // compares in constant time    }
    private static void send(HttpExchange exchange, int status, String json) throws IOException {        byte[] body = json.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().add("Content-Type", "application/json");        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class ServiceToServiceDemo {
    static String basic(String user, String password) {        String pair = user + ":" + password;        return "Basic " + Base64.getEncoder().encodeToString(pair.getBytes(StandardCharsets.UTF_8));    }
    static void call(HttpClient client, URI uri, String label, String authorization)            throws IOException, InterruptedException {        HttpRequest.Builder builder = HttpRequest.newBuilder(uri).GET();        if (authorization != null) {            builder.header("Authorization", authorization);        }        HttpResponse<String> response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString());        System.out.println(label + " -> " + response.statusCode() + " " + response.body());        response.headers().firstValue("WWW-Authenticate")                .ifPresent(value -> System.out.println("   WWW-Authenticate: " + value));    }
    public static void main(String[] args) throws Exception {        HttpServer server = StockService.start();        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/internal/stock/MOB-RN13");        HttpClient client = HttpClient.newHttpClient();        try {            // In a real service the password comes from an environment variable, never from code            call(client, uri, "order-service, right password", basic("order-service", "s3cret-from-env"));            call(client, uri, "order-service, old password  ", basic("order-service", "old-secret"));            call(client, uri, "no Authorization header      ", null);        } finally {            server.stop(0);        }    }}
Output
order-service, right password -> 200 {"sku":"MOB-RN13","stock":40}
order-service, old password   -> 401 {"error":"unauthorized"}
   WWW-Authenticate: Basic realm="stock"
no Authorization header       -> 401 {"error":"unauthorized"}
   WWW-Authenticate: Basic realm="stock"

What this code does

  • A tiny JDK HttpServer plays the stock service and accepts only the order service's secret; Java's HttpClient plays the order service and sends the header itself.
  • MessageDigest.isEqual compares the decoded bytes in constant time, and every failure gets the same 401 with WWW-Authenticate, like Spring's.
  • The secret is written in the code only so the demo runs on its own. A real service reads it from an environment variable and runs over HTTPS.

Basic is a sound choice for machine-to-machine calls over HTTPS that use a long random secret, not a person's password: a monitoring tool reading a metrics endpoint, or Maven downloading from a company's private package repository. The client is a program, so there is no pop-up, and the secret comes from an environment variable and can be rotated (replaced with a new one) on a schedule.

Four rules for such calls:

  • Always HTTPS, never plain HTTP outside your own laptop.
  • A random secret of 32 or more characters per calling service, from the environment, never in code or Git.
  • Compare secrets with MessageDigest.isEqual, which takes the same time whether the first or the last character is wrong.
  • For people using a website or a mobile app, prefer sessions or tokens (the next lessons).

Next step

Check your understanding

11 quick questions