Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
use your own login page, specify the url
- Only
/login
is allowed
WebSecurityConfig.java
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and() // every endpoint is protected
.formLogin() // use login page
.loginPage("/login") // use our cusotmized login page
.permitAll(); // allow everyone to visit this endpoint
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("user")
.password(passwordEncoder().encode("user"))
.roles("USER");
}
}
WebMVCConfig.java to map the endpoints to corresponding html page.
Default ViewResolver for thymeleaf has the prefix templates and suffix html
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/").setViewName("home");
}
}
templates/login.html
We call POST
/login
endpoint to pass username
and password
to Spring Security to validate
<!DOCTYPE html>
<html xmlns:th="http:/www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Login - Company ABC</title>
</head>
<body>
<div>
<form th:action="@{/login}" method="post" style="max-width: 400px; margin: 0 auto;">
<p>
E-mail: <input type="email" name="username" required />
</p>
<p>
Password: <input type="password" name="password" required />
</p>
<p>
<input type="submit" value="Login" />
</p>
</form>
</div>
</body>
</html>
By default, Spring Security uses the field names username and password
templates/error.html to replace default whiltelabel error page
<!DOCTYPE html>
<html>
<head>
<title>Error occurred</title>
</head>
<body>
<h1>Error occurred</h1>
<p>
An error has occurred. Please contact the administrator; - template generic
</p>
</body>
</html>
templates/home.html as the index page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Home
</body>
</html>