Phase 1, create a MVC application
Step 1, add dependencies
<dependency>
<groupId>org.springframework.boot</groupId>.
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Step 2, MVCConfig.java
@Configuration
public class MCVConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/logout").setViewName("logout");
}
}
Step 3, html under resources / templates/
home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<!-- link to the /hello page -->
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>
hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<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>
Now you can view
http://localhost:8080/
, http://localhost:8080/home
, http://localhost:8080/hello
Phas3 2, secure the application
Step 1, add dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Spring Security has default settings
Step 2, add WebSecurityConfig.java to override default setting
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// what uri open or close
.authorizeRequests()
// open
.antMatchers("/", "/home", "/logout").permitAll()
// close
.anyRequest().authenticated()
// use customized login page, Spring Security's logout page will be void
.and()
.formLogin().loginPage("/login").permitAll()
// use Spring Security default login page
// .and()
// .formLogin().permitAll()
// when user call /login?logout, they don't need to login again, this uri is open
.and()
.logout().permitAll();
}
References