HTTP Basic

How HTTP Basic Works

With HTTP Basic the client sends username:password, Base64-encoded, in the Authorization header of every request. There is no login page and no session needed, which makes it handy for scripts, internal tools and quick API testing.

Example

Base64 is an encoding, not encryption. Anyone who sees the header can decode it, which is why Basic auth must only be used over HTTPS:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        String credentials = "asha:asha123";
        String encoded = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
        System.out.println("Authorization: Basic " + encoded);

        // What BasicAuthenticationFilter (or an attacker sniffing HTTP) does:
        String header = "Basic " + encoded;
        String decoded = new String(Base64.getDecoder().decode(header.substring(6)), StandardCharsets.UTF_8);
        int colon = decoded.indexOf(':');
        System.out.println("username = " + decoded.substring(0, colon));
        System.out.println("password = " + decoded.substring(colon + 1));
    }
}

Output

Authorization: Basic YXNoYTphc2hhMTIz
username = asha
password = asha123

Enabling It

http
    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
    .httpBasic(basic -> basic.realmName("ShopEase API"))
    .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))  // no session for API calls
    .csrf(csrf -> csrf.disable());   // safe: no cookies are used

Example

Without and with credentials (curl -u builds the header for you):

curl -i localhost:8080/api/cart
curl -i -H "Authorization: Basic YXNoYTphc2hhMTIz" localhost:8080/api/cart

Example output

HTTP/1.1 401
WWW-Authenticate: Basic realm="ShopEase API"

HTTP/1.1 200
Content-Type: application/json

{"items":[{"productId":1,"name":"Wireless Mouse","quantity":2,"price":799.0}],"total":1598.0}

Basic vs Form Login vs Tokens

HTTP BasicForm loginJWT (medium level)
Password sentevery requestonceonce
Statenoneserver sessionnone
Good forscripts, internal tools, testingserver-rendered websitesSPAs, mobile apps, microservices
Logoutnot really (browser caches it)yestoken expiry

Tip: The WWW-Authenticate: Basic header makes browsers show an ugly popup. For a browser-facing app, prefer form login.