Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Getting Started

Your First Secured Spring Application

Add the Spring Security starter to a Boot app, see the generated password and login page, and learn exactly what the framework does before you configure anything.

The best way to understand Spring Security is to add it to a tiny application and look at what changes. You write no security code at all: one dependency is enough to lock every endpoint. This lesson walks through that experience, explains each default, and then shows how to replace the single generated user with your own.

You should know how a Spring Boot web application starts and what a @RestController is. If not, read Spring Boot Introduction first.

The application

A minimal Boot project has one controller. Nothing here mentions security.

Java
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController
class HelloController {
    @GetMapping("/hello")
    String hello() {
        return "Hello, stranger";
    }
}

Without the security starter, GET /hello returns 200 and the text. Now add the starter next to spring-boot-starter-web:

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

For Gradle it is implementation("org.springframework.boot:spring-boot-starter-security"). Restart the application and nothing in your code has changed, but the behavior has.

What you see after the restart

In the startup log there is a line like this one (the password is a random UUID and differs on every start):

TEXT
Using generated security password: 5d1f3b0e-7e3a-4a53-9f6a-0a7b6c1d2e44

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

Now call the endpoint without credentials:

TEXT
$ curl -i http://localhost:8080/hello
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm"

And with the generated credentials (user name user):

TEXT
$ curl -u user:5d1f3b0e-7e3a-4a53-9f6a-0a7b6c1d2e44 http://localhost:8080/hello
Hello, stranger

A browser behaves differently: it asks for HTML, so it is redirected to a login page at /login that Spring generates for you, and after a successful login it is sent back to the page it wanted. The same application, two different behaviors; the choice depends on the Accept header, and you will see why in a moment.

Everything that was switched on

The starter activates Boot's security auto-configuration. By default:

  1. Every request needs authentication (anyRequest().authenticated()).
  2. A single in-memory user named user exists with the generated password and the role USER.
  3. Form login (generated page at /login) and HTTP Basic are both enabled.
  4. Logout is available through POST /logout (and a generated logout page).
  5. CSRF protection is on, so POST, PUT, PATCH and DELETE need a token.
  6. Security headers are added to every response.
  7. Session management: sessions are created when needed and protected against fixation.

You can reproduce the log-in decision with a small piece of logic: if the client prefers HTML, redirect it to the login page, otherwise answer 401 with a Basic challenge. The following stand-in decides that, and also generates a password the way the real default does (a random UUID) and decodes a Basic header.

Java Default entry point and generated password

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.

Choosing your own user

The generated password changes with every restart, which is fine for a ten-minute experiment and useless for anything else. The quickest way to pin a user is with properties:

PROPERTIES
spring.security.user.name=ana
spring.security.user.password=s3cret
spring.security.user.roles=USER,ADMIN

This is still a single in-memory user and the password sits in a config file, so use it only for local work. The proper approach is to define your own UserDetailsService bean, covered in UserDetailsService and user stores. The moment you declare such a bean, Boot backs off: the generated user disappears. That "back off when you define your own" rule is how almost all Boot auto-configuration works.

Opening up one endpoint

Real applications need public pages (a landing page, a health check). With the defaults you must declare a SecurityFilterChain bean. Defining one replaces the whole default chain, so you must restate what you still want:

Java
@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/public/**").permitAll()
                .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

Read it top to bottom: the home page and anything under /public/ are open; everything else needs login; users may log in through the form or Basic. If you forget formLogin, browsers get a bare 403 instead of a login page, a very common first mistake.

A first look at the pieces

Even this small configuration touches the main actors, which later lessons explain one at a time:

  • HttpSecurity: a builder that assembles a list of filters (next chapter).
  • UserDetailsService: loads the user by name when someone logs in.
  • PasswordEncoder: checks the submitted password against the stored hash.
  • AuthenticationManager: coordinates the check.
  • SecurityContextHolder: remembers who is logged in for the rest of the request.

A quick request simulation

To feel the "closed by default" rule, the next stand-in applies first-match rules like the configuration above to several URLs and users.

Java Rules: public pages and the rest

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.

Mistakes beginners make

  • Leaving the generated password in production. The log line itself says so. Always provide a real user source.
  • Returning to the old adapter style. extends WebSecurityConfigurerAdapter no longer exists; use a SecurityFilterChain bean.
  • Expecting a bean to add to the defaults. A SecurityFilterChain bean replaces the default chain entirely.
  • Disabling security to "make it work". http.csrf(csrf -> csrf.disable()) is sometimes right for a stateless API, but never as a reflex for a failing POST. A later chapter explains how to do it correctly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You add spring-boot-starter-security and change nothing else. What happens to GET /hello without credentials?

    All requests need authentication by default, so an anonymous call is challenged.
  2. 2. Where does the default user's password come from?

    Boot generates a random password for the user named user. Set spring.security.user.password or define a UserDetailsService to change it.
  3. 3. You declare your own SecurityFilterChain bean with only authorizeHttpRequests(...). Browsers now get a plain 403 instead of a login page. Why?

    Your bean replaces the whole default chain. Form login and HTTP Basic must be restated if you want them.
  4. 4. What happens to the generated user once you define your own UserDetailsService bean?

    Boot auto-configuration backs off when you provide your own bean.

Summary

  • One dependency locks the whole application: authentication everywhere, form login, HTTP Basic, CSRF and headers.
  • The default user is user with a random UUID password printed in the log.
  • spring.security.user.* pins a user for experiments only.
  • Your own SecurityFilterChain bean replaces the default chain; restate form login or Basic if you need them.
  • Clients that prefer HTML are redirected to /login; others get 401 with a Basic challenge.

Next: Core concepts: Authentication, SecurityContext and authorities