Following example shows how to configure JDBC authentication in Spring Boot. Check out this tutorial to see how to do that in plain Spring Security.
Example
We are using H2 in-memory database to persist the usernames/passwords and Thymeleaf for views.
pom.xml<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</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-jdbc</artifactId>
</dependency>
Configuration class
@SpringBootApplication
public class ExampleMain {
@Bean
public WebSecurityConfigurerAdapter webSecurityConfig(DataSource dataSource) {
return new WebSecurityConfigurerAdapter() {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.dataSource(dataSource);
}
};
}
public static void main(String[] args) {
SpringApplication.run(ExampleMain.class);
}
}
SQL scripts
src/main/resources/schema.sqlcreate table users(
username varchar_ignorecase(50) not null primary key,
password varchar_ignorecase(200) not null,
enabled boolean not null
);
create table authorities (
username varchar_ignorecase(50) not null,
authority varchar_ignorecase(50) not null,
constraint fk_authorities_users foreign key(username) references users(username)
);
src/main/resources/data.sqlinsert into users (username, password, enabled) values ('bob', '$2a$10$/ns.CwZ9sdhQaVjw/bwBQeelnmTZTI19trLtyY/bjbIVUokAckX8y', true);
insert into authorities (username, authority) values ('bob', 'ROLE_USER');
insert into users (username, password, enabled) values ('sara', '$2a$10$WPDbKLCRnV0UrkEs2IEtUejsZiicxt0/GhUcOkg2.UscjBi8tOmxa', true);
insert into authorities (username, authority) values ('sara', 'ROLE_ADMIN');
Password encoding
In above script we have encoded the passwords by using following utility class. We are using BCryptPasswordEncoder in this example.
public class PasswordEncoderUtil {
public static void main(String[] args) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encoded = encoder.encode("123");//bob's password
System.out.println(encoded);
encoded = encoder.encode("234");//sara's password
System.out.println(encoded);
}
}
MVC controller
@Controller
public class AppController {
@RequestMapping("/**")
public String handler(ModelMap model, HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
model.addAttribute("uri", request.getRequestURI());
model.addAttribute("user", auth.getName());
model.addAttribute("roles", auth.getAuthorities());
return "app";
}
}
Thymeleaf view
src/main/resources/templates/app.html<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<body>
<h2>Spring Secured App</h2>
<p>app content ......... at uri <span th:text="${uri}"/></p>
<p>User: <span th:text="${user}"/></p>
<p>Roles: <span th:text="${roles}"/></p>
<br/>
<form action="/logout" method="post">
<input type="hidden"
th:name="${_csrf.parameterName}"
th:value="${_csrf.token}"/>
<input type="submit" value="Logout">
</form>
</body>
</html>
Running example
To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):
mvn spring-boot:run Or run the main method class from IDE.
Output
Accessing http://localhost:8080 in the browser:
On entering valid user/password and submitting:
Example ProjectDependencies and Technologies Used: - Spring Boot 2.0.2.RELEASE
Corresponding Spring Version 5.0.6.RELEASE - spring-boot-starter-security : Starter for using Spring Security.
Uses org.springframework.security:spring-security-web version 5.0.5.RELEASE - spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container.
- spring-boot-starter-thymeleaf : Starter for building MVC web applications using Thymeleaf views.
Uses org.thymeleaf:thymeleaf-spring5 version 3.0.9.RELEASE - spring-boot-starter-jdbc : Starter for using JDBC with the HikariCP connection pool.
Uses org.springframework:spring-jdbc version 5.0.6.RELEASE Uses com.zaxxer:HikariCP version 2.7.9 - h2 1.4.197: H2 Database Engine.
- JDK 1.8
- Maven 3.3.9
|