Skip to content

Lab 18 - Secure View All Orders

We'd like to "lock down" the "view all orders" screen so it can only be seen by an admin.

A. Configure Dependencies

Add the following dependencies to the pom.xml file to pull in the necessary security dependencies.


B. Configure the Security Adapter

Configure the security so that the /coffee-orders page can only be accessed by an ADMIN.

Add the following class, named SecurityConfig to your project:

package com.welltestedlearning.cvm;

import org.springframework.beans.factory.annotation.Autowired;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

  // @formatter:off
  protected void configure(HttpSecurity http) throws Exception {
  // @formatter:on

  // @formatter:off
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  // @formatter:on

C. Add Login Page

Create a new template, called login.html:

<!DOCTYPE html>
<html xmlns:th="">
  <title>Admin Login Page</title>
<h2>Admin Login Page</h2>

<form th:action="@{/login}" method="post">
  <p th:if="${loginError}">Invalid username and/or password.</p>
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" autofocus="autofocus"/>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password"/>
  <input type="submit" value="Log in"/>

D. Create Login Controller

Create a controller class, called WebLoginController that will serve up and process the login template:

public class WebLoginController {

  public String login() {
    return "login";

  public String loginError(Model model) {
    model.addAttribute("loginError", true);
    return "login";

Now try going to the view all orders page (localhost:8080/coffee-orders), and you'll see that you need to log in first.

Also try logging in with incorrect credentials to see what happens.

E. Add Security to Template

The Thymeleaf security tags start with sec and you can restrict parts of a page like this:

<div sec:authorize="isAuthenticated()">
  This content is only shown to authenticated users.

To use the sec prefix, you'll need to add the namespace like this, at the top of the HTML file:

<html xmlns=""

You can also display information about the logged-in user like this:

<p>Logged user: <span sec:authentication="name">Bob</span></p>
<p>Roles: <span sec:authentication="principal.authorities">user</span></p>

Add these to the page and then view it to see the name and its roles.