下面我将为你详细讲解“SpringBoot Security安装配置及Thymeleaf整合”的完整攻略。
安装
首先需要在pom.xml中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置
添加完依赖之后,需要在Spring Boot应用程序上启用安全性。对于这个任务,我们需要编写一个配置类,并使用@EnableWebSecurity注释激活Spring Security的Web安全性功能:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}
在上面的代码中,我们声明了一个WebSecurityConfig类并扩展了WebSecurityConfigurerAdapter类。我们还使用@EnableWebSecurity注释将启用Web安全性,并在configure()方法中配置HttpSecurity以定义我们的安全性规则。在configureGlobal()方法中,我们将用户的认证委托给UserService。
Thymeleaf整合
Thymeleaf是一种针对网站和Java应用程序的先进的Web和模板引擎。为了将Thymeleaf与Spring Security整合,我们需要添加一个Thymeleaf安全Dialect。这是通过在pom.xml上添加以下依赖来完成的:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
此外,在Spring Boot应用程序上配置Thymeleaf模板解析器时,我们需要添加一个安全方言:
@Configuration
public class ThymeleafConfig implements WebMvcConfigurer {
private final ApplicationContext applicationContext;
public ThymeleafConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
engine.addDialect(new SpringSecurityDialect());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
registry.viewResolver(resolver);
}
}
示例
接下来,我将使用两个示例来说明SpringBoot Security安装配置及Thymeleaf整合。
示例1:基本认证
首先定义一个UserController类,其中包含了一个login()方法和一个logout()方法:
@Controller
public class UserController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/logout")
public String logout() {
return "redirect:/login?logout=true";
}
}
然后,我们需要创建一个login.html模板来显示登录页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h1>Login</h1>
<form th:action="@{/login}" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
为了测试我们的代码,我们需要创建一个安全配置类和一个用户服务类:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("password"))
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Service
public class UserService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username.equals("user")) {
return User.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
} else {
throw new UsernameNotFoundException("User not found.");
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
示例2:自定义登录认证
首先定义一个CustomUserDetails类来扩展Spring Security的UserDetails接口:
public class CustomUserDetails implements UserDetails {
private final String username;
private final String password;
private final Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
然后我们需要扩展UserDetailsService接口,并在其中进行自定义的用户认证:
@Service
public class UserService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username.equals("user")) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new CustomUserDetails("user", passwordEncoder().encode("password"), authorities);
} else {
throw new UsernameNotFoundException("User not found.");
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
最后,在WebSecurityConfig类中,我们需要使用自定义的UserDetailsService,并对我们的用户名和密码进行验证:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}
这两个示例可以帮助你理解SpringBoot Security安装配置及Thymeleaf整合的过程。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot Security安装配置及Thymeleaf整合 - Python技术站