Step‑by‑Step Spring Security Demo: Login, Logout and Page Protection

This tutorial walks through a complete Spring Boot demo that sets up Maven dependencies, creates Thymeleaf front‑end pages (home, login, hello), implements a main Application class, a HomeController, and a WebSecurityConfig to secure the application with in‑memory authentication, illustrating how to protect URLs, configure a custom login page, and enable logout functionality.

Programmer DD
Programmer DD
Programmer DD
Step‑by‑Step Spring Security Demo: Login, Logout and Page Protection

Overview

The article provides a hands‑on example of building a Spring Boot application secured with Spring Security. It covers project structure, Maven configuration, front‑end Thymeleaf templates, the main Java entry point, controller mappings, and a security configuration class that defines authentication and authorization rules.

Project Structure

The demo follows the standard Spring Boot layout. Key directories include src/main/java for Java sources and src/main/resources/templates for Thymeleaf HTML files.

Maven Dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

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

Front‑End Pages (Thymeleaf)

home.html – a simple welcome page with a link to /hello:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spring Security Example</title>
  </head>
  <body>
    <h1>Welcome!</h1>
    <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
  </body>
</html>

login.html – custom login page displaying error or logout messages and a form that posts to /login:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spring Security Example</title>
  </head>
  <body>
    <div th:if="${param.error}">Invalid username and password.</div>
    <div th:if="${param.logout}">You have been logged out.</div>
    <form th:action="@{/login}" method="post">
      <div><label>UserName: <input type="text" name="username"/></label></div>
      <div><label>Password: <input type="password" name="password"/></label></div>
      <div><input type="submit" value="Sign In"/></div>
    </form>
  </body>
</html>

hello.html – a page shown after successful authentication, greeting the logged‑in user and providing a logout button:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello World!</title>
  </head>
  <body>
    <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
    <form th:action="@{/logout}" method="post">
      <input type="submit" value="Sign Out"/>
    </form>
  </body>
</html>

Main Application Class

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

Controller (HomeController)

@Controller
public class HomeController {
    @RequestMapping("/")
    public String home() {
        return "home"; // resolves to home.html
    }

    @RequestMapping("/login")
    public String login() {
        return "login"; // resolves to login.html
    }

    @RequestMapping("/hello")
    public String hello() {
        return "hello"; // resolves to hello.html
    }
}

Security Configuration (WebSecurityConfig)

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()               // allow public access to home page
                .anyRequest().authenticated()                // protect all other URLs
            .and()
                .formLogin()
                .loginPage("/login")                     // custom login page
                .permitAll()
            .and()
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // In‑memory user for demonstration: username=anyCode, password=password, role=USER
        auth.inMemoryAuthentication()
                .withUser("anyCode").password("password").roles("USER");
    }
}

Running the Demo

Start the application with mvn spring-boot:run (or run the Application class from an IDE). Access http://localhost:8080/ to see the home page. Clicking the link navigates to /hello, which triggers the login page. After entering the credentials anyCode / password, the user is redirected to the hello page, where the username is displayed and a logout button is provided.

Key Takeaways

Spring Security can be quickly integrated into a Spring Boot project via the spring-boot-starter-security starter.

Custom login and logout pages are defined with Thymeleaf templates and wired through .formLogin().loginPage("/login").

URL authorization rules are expressed with .authorizeRequests(), allowing public access to selected endpoints while protecting the rest.

In‑memory authentication is useful for demos; production systems should use a persistent user store and password encoding.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootThymeleafWeb Authenticationspring-security
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.