Skip to lesson

Adding the starter and the default login

ShopLite's API lets anyone change a price or read a customer. One new dependency changes that at once: every endpoint stops answering strangers. What does the owner see, and how does a developer sign in again?

Adding spring-boot-starter-security

Spring Security is the Spring library that checks who is calling and what they may do, before a request reaches any controller.

Add the starter to pom.xml with no version, plus its test starter. The Spring Boot 4.1 parent picks the matching Spring Security 7 version.

Example 1 · pom.xml: the security starters

Runs in: the shoplite-api Spring Boot project

XML
<!-- pom.xml: inside <dependencies> --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-security</artifactId></dependency><!-- for tests: @WithMockUser, httpBasic() and friends --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-security-test</artifactId>    <scope>test</scope></dependency>
Sample output
$ ./mvnw dependency:tree -Dincludes=org.springframework.security
...
[INFO] com.shoplite:shoplite-api:jar:1.0.0
[INFO] +- org.springframework.boot:spring-boot-starter-security:jar:4.1.1:compile
[INFO] |  \- org.springframework.boot:spring-boot-security:jar:4.1.1:compile
[INFO] |     +- org.springframework.security:spring-security-config:jar:7.1.1:compile
[INFO] |     |  \- org.springframework.security:spring-security-core:jar:7.1.1:compile
[INFO] |     |     \- org.springframework.security:spring-security-crypto:jar:7.1.1:compile
[INFO] |     \- org.springframework.security:spring-security-web:jar:7.1.1:compile
[INFO] \- org.springframework.boot:spring-boot-starter-security-test:jar:4.1.1:test
[INFO]    \- org.springframework.boot:spring-boot-security-test:jar:4.1.1:test
[INFO]       \- org.springframework.security:spring-security-test:jar:7.1.1:test

What this code does

  • No <version> on either starter: the Spring Boot 4.1.1 parent chooses Spring Security 7.1.1 for you.
  • spring-security-config holds the configuration DSL, -core the users and authentication, -web the filters, -crypto the password encoders.
  • The test starter only adds test helpers; it never ends up in the jar you deploy.

Why now? Anyone who can reach the server can PATCH /api/v1/products/6 and change a price, or read every customer; the SECURITY.md from the last module lists these risks. spring-boot-starter-security is the first defence: nothing gets through until it is allowed.

spring-boot-starter-security-test brings @WithMockUser and the httpBasic() helper that the tests in this module use.

Never write a <version> for these starters. A hand-picked Spring Security version that does not match Spring Boot is a classic source of NoSuchMethodError at startup.

What happens at once: 401 and the generated password

401 Unauthorized is the HTTP status for "I do not know who you are": the request had no valid credentials.

Start the app and call the API with no credentials. The startup log prints a generated password, and the answer is 401.

Example 2 · Startup log and the first 401

Runs in: the shoplite-api Spring Boot project

Terminal
# after adding the starter: build, start, and call the API without credentials./mvnw clean package -DskipTestsjava -jar target/shoplite-api-1.0.0.jarcurl -i http://localhost:8080/api/v1/products/1curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/actuator/health
Sample output
$ ./mvnw clean package -DskipTests
$ java -jar target/shoplite-api-1.0.0.jar
...
... WARN 30656 --- [shoplite-api] [           main] .s.a.UserDetailsServiceAutoConfiguration :

Using generated security password: afdb74de-f0f5-4c92-ab04-90cd481dec83

This generated password is for development use only. Your security configuration must be updated before running your application in production.

... INFO 30656 --- [shoplite-api] [           main] r$InitializeUserDetailsManagerConfigurer : Global AuthenticationManager configured with UserDetailsService bean with name inMemoryUserDetailsManager
... INFO 30656 --- [shoplite-api] [           main] o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 8080 (http) with context path '/'

(second terminal)
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 401
Set-Cookie: JSESSIONID=058F2504912E0B5074FECB3120F3508D; Path=/; HttpOnly
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-Length: 0
Date: Fri, 16 Oct 2026 06:24:50 GMT

$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/actuator/health
200

What this code does

  • The WARN line from UserDetailsServiceAutoConfiguration prints the random password for the user user; it changes on every start.
  • The product read now answers 401 with an empty body. WWW-Authenticate: Basic realm="Realm" invites the client to sign in with HTTP Basic.
  • Spring Security also adds safety headers to every response (X-Frame-Options, Cache-Control: no-store and others), and Boot keeps /actuator/health open.

Every endpoint of shoplite-api now answers 401 to a plain curl, even GET /api/v1/products/1, which worked a minute ago. You changed no controller: Spring Security answers before the controller is reached. Boot also creates one user, named user, with a random password printed in the startup log as Using generated security password: ...; a new one is made on every start.

The 401 response has an empty body and a WWW-Authenticate: Basic header, which tells the client how to sign in. Boot leaves only /actuator/health open, so load balancers can still check the app. Your existing @WebMvcTest tests fail too: in shoplite-api, mvn test reports Tests run: 6, Failures: 6 for ProductControllerTest. That is expected; the Permitting public endpoints lesson fixes them.

Predict the output

What does the API answer?

The starter is added and no SecurityConfig exists yet.

Round 1 of 3

A guest asks for a product.

# the starter is on the classpath
curl -i http://localhost:8080/api/v1/products/1

Calling the API with curl -u, and the login page

HTTP Basic is sign-in by header: the client sends Authorization: Basic plus username:password encoded in Base64 with every request.

Send the generated password with curl -u, try a wrong one, look at the real header and ask for HTML like a browser. Then decode a header in plain Java.

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

Runs in: the shoplite-api Spring Boot project

Terminal
curl -i -u user:afdb74de-f0f5-4c92-ab04-90cd481dec83 http://localhost:8080/api/v1/products/1curl -i -u user:wrong-password http://localhost:8080/api/v1/products/1curl -v -u user:afdb74de-f0f5-4c92-ab04-90cd481dec83 http://localhost:8080/api/v1/categories/2curl -i -H "Accept: text/html" http://localhost:8080/api/v1/products/1
Sample output
$ curl -i -u user:afdb74de-f0f5-4c92-ab04-90cd481dec83 http://localhost:8080/api/v1/products/1
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: 135
Date: Fri, 16 Oct 2026 06:24:53 GMT

{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}

$ curl -i -u user:wrong-password http://localhost:8080/api/v1/products/1
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
...
Content-Length: 0

$ curl -v -u user:afdb74de-f0f5-4c92-ab04-90cd481dec83 http://localhost:8080/api/v1/categories/2 2>&1 | grep -E "^[<>] (GET|Authorization|HTTP)"
> GET /api/v1/categories/2 HTTP/1.1
> Authorization: Basic dXNlcjphZmRiNzRkZS1mMGY1LTRjOTItYWIwNC05MGNkNDgxZGVjODM=
< HTTP/1.1 200

$ curl -i -H "Accept: text/html" http://localhost:8080/api/v1/products/1
HTTP/1.1 302
Set-Cookie: JSESSIONID=B287888AE1DC2A95EE9F2469D3EC414A; Path=/; HttpOnly
...
Location: http://localhost:8080/login
Content-Length: 0

What this code does

  • With the right password the response is the normal 200 JSON. A wrong password gives the same 401 as no password at all.
  • curl -v shows what -u really sends: Authorization: Basic followed by Base64 text, on every single request.
  • A request that asks for HTML (like a browser) is redirected with 302 to /login, the default sign-in page. A JSON client never sees that page.

Example 4 · Base64 is not secret: decoding a Basic header

BasicHeaderDemo.javaJava
import java.nio.charset.StandardCharsets;import java.util.Base64;
public class BasicHeaderDemo {
    static String encode(String username, String password) {        String pair = username + ":" + password;        return Base64.getEncoder().encodeToString(pair.getBytes(StandardCharsets.UTF_8));    }
    static void decode(String headerValue) {        String token = headerValue.substring("Basic ".length());        String pair = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);        int colon = pair.indexOf(':');        System.out.println("Header:   " + headerValue);        System.out.println("Username: " + pair.substring(0, colon));        System.out.println("Password: " + pair.substring(colon + 1));    }
    public static void main(String[] args) {        // What curl -u dev:shop-dev-2026 sends        String header = "Basic " + encode("dev", "shop-dev-2026");        decode(header);        System.out.println();
        // A header copied from a real curl -v run: anyone who sees it can read the password        decode("Basic dXNlcjphZmRiNzRkZS1mMGY1LTRjOTItYWIwNC05MGNkNDgxZGVjODM=");    }}
Output
Header:   Basic ZGV2OnNob3AtZGV2LTIwMjY=
Username: dev
Password: shop-dev-2026

Header:   Basic dXNlcjphZmRiNzRkZS1mMGY1LTRjOTItYWIwNC05MGNkNDgxZGVjODM=
Username: user
Password: afdb74de-f0f5-4c92-ab04-90cd481dec83

What this code does

  • encode builds exactly what curl -u dev:shop-dev-2026 sends: username:password in Base64.
  • decode reverses it with one JDK call. The second header was copied from the curl -v output in Example 3, and the generated password comes straight out.
  • So Basic authentication is only acceptable over HTTPS, where the whole header is encrypted on the way.

With the generated password the request answers 200 again; with a wrong one it stays 401. A browser asks for HTML, so it is redirected (302) to /login, a "Please sign in" page made by Spring Security; curl asks for anything, so it gets 401 with WWW-Authenticate.

Watch two things. Base64 is an encoding, not encryption: anyone who sees the header can read the password, so Basic is only safe over HTTPS. And a POST with the right password still answers 401 for now; the next lesson explains it (the CSRF filter) and the configuration lesson fixes it.

A development user with spring.security.user.*

spring.security.user.* are the properties name, password and roles that set the one in-memory user Spring Boot creates, instead of user with a random password.

Put the properties in application-dev.properties and read the password from an environment variable, so the file in Git holds no secret.

Example 5 · application-dev.properties: a development user

Runs in: the shoplite-api Spring Boot project

Text
# src/main/resources/application-dev.properties (added at the end)# Temporary development user: one user kept in memory (database users replace it in the next module).# The password comes from an environment variable, never from this file.spring.security.user.name=${SHOPLITE_DEV_USER:dev}spring.security.user.password=${SHOPLITE_DEV_PASSWORD}spring.security.user.roles=ADMIN
Sample output
# Windows PowerShell: $env:SHOPLITE_DEV_PASSWORD = "shop-dev-2026"
$ export SHOPLITE_DEV_PASSWORD=shop-dev-2026
$ java -jar target/shoplite-api-1.0.0.jar
... No active profile set, falling back to 1 default profile: "dev"
... Tomcat started on port 8080 (http) with context path '/'
(no "Using generated security password" line any more)

$ curl -i -u dev:wrong-password http://localhost:8080/api/v1/customers/1
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
...

$ curl -i -u "dev:$SHOPLITE_DEV_PASSWORD" http://localhost:8080/api/v1/customers/1
HTTP/1.1 200
...
Content-Type: application/json

{"id":1,"fullName":"Asha Rao","email":"asha.rao@example.com","phone":"9876543201","createdAt":"2026-05-04T10:15:00+05:30"}

# A new terminal where the variable was never set:
$ java -jar target/shoplite-api-1.0.0.jar
...
Caused by: org.springframework.util.PlaceholderResolutionException: Could not resolve placeholder 'SHOPLITE_DEV_PASSWORD' in value "${SHOPLITE_DEV_PASSWORD}"

What this code does

  • ${SHOPLITE_DEV_USER:dev} uses the variable if set, otherwise dev. ${SHOPLITE_DEV_PASSWORD} has no default on purpose, so a missing password stops the app at startup.
  • With the variable set, the generated-password line disappears and dev signs in. "dev:$SHOPLITE_DEV_PASSWORD" lets the shell fill in the password, so it never appears in your command history.
  • Started with --spring.profiles.active=prod, the dev user does not exist: dev gets 401 and Boot prints a generated password again.

The file is committed to Git, so the password must not be in it: write ${SHOPLITE_DEV_PASSWORD} and set that environment variable in your terminal. If the variable is missing, the app refuses to start with Could not resolve placeholder, which is what you want: no silent default password. spring.security.user.roles gives the user its roles.

This user is a development tool, not a login system: one shared account, a plain-text password in memory, no sign-up and no lockout. In the prod profile it does not exist at all, and Boot falls back to a generated password; the next module replaces it with users stored in MySQL with BCrypt hashes.

Order of execution

Set up the dev user safely

Put the steps in the order you would do them.

On Windows PowerShell set the variable with $env:SHOPLITE_DEV_PASSWORD = "your-password"; on macOS use export SHOPLITE_DEV_PASSWORD=your-password. It lasts until you close that terminal.

Spring Security 7 and outdated tutorials

Spring Security 7 is the version that comes with Spring Boot 4. It removed the old configuration style that many tutorials still show, so code copied from them does not compile.

Compile an outdated tutorial against Spring Security 7 and read the errors.

Example 6 · An outdated tutorial against Spring Security 7

Runs in: the shoplite-api Spring Boot project

SecurityConfig.javaJava
// Copied from a 2021 tutorial (Spring Security 5). Does NOT compile on Spring Security 7.import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()                .antMatchers("/api/v1/products/**").permitAll()                .anyRequest().authenticated()                .and()                .httpBasic();    }}
Sample output
$ ./mvnw compile
[ERROR] COMPILATION ERROR :
[ERROR] .../security/SecurityConfig.java:[6,72] cannot find symbol
  symbol:   class WebSecurityConfigurerAdapter
  location: package org.springframework.security.config.annotation.web.configuration
[ERROR] .../security/SecurityConfig.java:[11,37] cannot find symbol
  symbol: class WebSecurityConfigurerAdapter
[ERROR] .../security/SecurityConfig.java:[13,5] method does not override or implement a method from a supertype
[ERROR] .../security/SecurityConfig.java:[15,13] cannot find symbol
  symbol:   method authorizeRequests()
  location: variable http of type org.springframework.security.config.annotation.web.builders.HttpSecurity

# A 2022 tutorial with the no-argument methods:
http.httpBasic();
http.csrf().disable();

[ERROR] ...: error: method httpBasic in class ...HttpSecurity cannot be applied to given types;
        http.httpBasic();
            ^
  required: org.springframework.security.config.Customizer<...HttpBasicConfigurer<...HttpSecurity>>
  found:    no arguments
[ERROR] ...: error: method csrf in class ...HttpSecurity cannot be applied to given types;

What this code does

  • The class WebSecurityConfigurerAdapter no longer exists, so the import and extends fail, and @Override has nothing to override.
  • authorizeRequests() is gone too; antMatchers and .and() would fail next. The second snippet shows that the no-argument httpBasic() and csrf() are removed in version 7.
  • The fix is the SecurityFilterChain bean with lambdas, written in the SecurityFilterChain configuration lesson.

Three signs tell you a tutorial is outdated:

  • extends WebSecurityConfigurerAdapter with configure(HttpSecurity http): removed in Spring Security 6.0. Today you declare a SecurityFilterChain bean.
  • antMatchers(...), mvcMatchers(...) and authorizeRequests(): removed. Today it is authorizeHttpRequests(...) with requestMatchers(...).
  • .and() chains and no-argument calls such as httpBasic() or csrf().disable(): removed in Spring Security 7. Today every part takes a lambda: httpBasic(Customizer.withDefaults()), csrf(csrf -> csrf.disable()).

When you search for help, add "Spring Security 7" or "Spring Boot 4" and check the date.

Fix the error

Translate the old snippet

Read the compiler error, then pick the line that fixes it.

Round 1 of 3

An old method name.

http
.authorizeRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());

Error

error: cannot find symbol
  symbol:   method authorizeRequests(...)
  location: variable http of type HttpSecurity

Next step

Check your understanding

11 quick questions