Adding the Starter

Add the Dependency

Add spring-boot-starter-security to the ShopEase project (Spring Boot 3.x brings Spring Security 6.x):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Gradle: implementation 'org.springframework.boot:spring-boot-starter-security'.

What Happens Immediately

Without writing a single line of security code, Spring Boot auto-configuration:

  1. Protects every URL: all requests need authentication.
  2. Creates one user named user with a random password printed in the log.
  3. Adds a generated login page at /login and a logout page at /logout.
  4. Enables HTTP Basic for API clients and form login for browsers.
  5. Turns on CSRF protection, session fixation protection and secure response headers.

Example

Start the app and look at the log:

./mvnw spring-boot:run

Example output

INFO  ... Tomcat started on port 8080 (http) with context path '/'
WARN  ... UserDetailsServiceAutoConfiguration :

Using generated security password: 3f6c1a2e-8b47-4d0e-9a51-7c2d9e4b8f10

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

INFO  ... Started ShopEaseApplication in 2.8 seconds

Calling the API Now

Example

The products endpoint that worked yesterday now returns 401:

curl -i localhost:8080/api/products

Example output

HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0

With Credentials

Send the generated credentials with HTTP Basic (-u user:password):

curl -i -u user:3f6c1a2e-8b47-4d0e-9a51-7c2d9e4b8f10 localhost:8080/api/products

Example output

HTTP/1.1 200
Content-Type: application/json

[{"id":1,"name":"Wireless Mouse","price":799.0,"stock":120,"category":"Electronics"}]

Note: A browser that opens http://localhost:8080/api/products is redirected (302) to /login instead, because Spring Security sees it asks for HTML.