Spring boot集成Spring security,Thymeleaf,自定义用户登陆验证
引言
这几天忙活着倒腾自己的毕设,是用spring boot开发的,然后就遇到了项目安全性的问题。想着反正自己折腾,就试试没用过的spring security好了,因为不满足于其自身携带的basic验证,所以要重写一些配置和方法。结果发现还有蛮多坑要踩的,这里记录一下,一方面总结一下所学的,然后也很久没写东西了,另一方面希望能帮到一些小伙伴,让小伙伴们少走一点弯路就更好了。
Spring security
spring security 可以很方便的帮我们处理一些安全问题,而且配置灵活。与spring boot和thymeleaf都能很好的互相协作。在spring boot项目的依赖,spring boot想目创建和thymeleaf这里就不细说了,security添加依赖,在pom.xml中添加:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 在thymeleaf中扩展spring secutity -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
然后是自定义的配置类,总共有两个:
/**
* 系统web配置
* @author krim
*
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/").setViewName("login");
}
}
看方法名字也知道这里是添加了两个controller,将”/login”和”/”的请求映射到了View名为”login”的文件,当然这个”login”就像controller里直接返回的字符串一样,后面还会被视图解析器解析到具体的文件
第二个配置类比较重要:
/**
* 系统安全配置
* @author krim
*
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
SessionRegistry sessionRegistry;
@Bean
public SessionRegistry getSessionR