文章暂不谈spring security源码,只简单记录快速搭建spring security实现登录、权限验证时,遇到的问题。
spring security快速搭建,分为两部分:配置部分、请求部分。配置部分会在项目启动时读取;请求部分就是经过security的一系列过滤器进行登录验证及权限验证。
先上demo的目录结构:
一、配置部分:
1、添加spring security依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、拦截规则配置、登录验证配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//自定义校验用户类
@Autowired
private UserServiceDao userServiceDao;
//自定义登陆成功后处理类
@Autowired
private LoginSuccessHandler loginSuccessHandler;
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/loginError").permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/home").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and()
.