文章目录
前言:SpringSecurity系列是比较高级的内容,需要有一定的基础才能学得懂,例如需要熟悉spring系列,熟悉filter和interceptor,还得有实际的开发经验;这个系列的内容也是按照读者已经具备以上条件来写的。若是有需要的可以看一下我之前写的 spring系列 和JavaWeb系列,如果你基础不好,相信对你有帮助,特别要重点看一下Spring Boot总结一 里的第七大点拦截器和过滤器,SpringSecurity就是基于这两个来实现的。需要源码的可以到这里下载 >> demo源码
SpringSecurity核心功能:
1、认证(你是谁)
2、授权(你能干什么)
3、攻击防护(防止伪造身份)
一、SpringSecurity基本原理:
1、基本原理
spring security基于表单认证原理
1.每个请求都要依次经过上面的这些过滤器和拦截器.
2.绿色的过滤器负责认证方式,比如默认的basic认证,表单认证以及后续短信认证都属于绿色的过滤器,是可以配置的,也可以修改位置的,其他的是框架写好的,不能改变(包括位置)。
3.橙色的过滤器是最后一个过滤器,相当于一个守门人,它决定用户是否认证和授权,可以根据不同的原因抛出不同异常。
4.蓝色部分ExceptionTranslationFiter是异常处理过滤器,它负责对橙色过滤器抛出的异常进行各种各样的处理,可根据具体情况可转到不同页面或返回不同的结果。
2、基本代码
引入相关的pom文件之后,在配置文件设置 security.basic.enabled = true
就开启springsecurity校验,security.basic.enabled = false
则不开启(默认为true);
WebSecurityConfigurerAdapter是springsecurity安全校验设备器,继承这个类,重写configure方法可设置校验规则,各种情况下的处理。
如下:
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ImoocAuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
@Autowired
private ImoocAuthenctiationFailureHandler imoocAuthenctiationFailureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//表单登录
.formLogin()
//配置自定义登录页
.loginPage("/imooc-signIn.html")
//登录表单接口,usernamepasswordAuthenticationfilter.attemptAuthentication方法处理的请求
.loginProcessingUrl("/authentication/form")
//登录成功处理的handler,失败类似,可以决定返回json
.successHandler(imoocAuthenticationSuccessHandler)
.failureHandler(imoocAuthenctiationFailureHandler)
.and()
//对请求授权
.authorizeRequests()
//访问这里的地址的时候不需要身份认证
.antMatchers("/imooc-singIn.html").permitAll()
//角色是admin的用户才有权限访问 "/user" 路径
.antMatchers("/user").hasRole("admin")
//除了上面antMatchers配置的之外所有请求都需要身份认证
.anyRequest()
//需要认证(登录)
.authenticated() ;
}
}
上面的代码中,有很多东西是可以根据实际需求改动的,简化到最简单时的代码如下:
http.formLogin()
.and()