spring security
Spring security 是一个强大的和高度可定制的身份验证和访问控制框架。它是确保基于Spring的应用程序的标准。更多请预览官方文档:https://spring.io/projects/spring-security 中文版文档:https://www.springcloud.cc/spring-security-zhcn.html
一、核心功能
认证
授权
攻击防护
二、原理
(一)整个框架的核心是一个过滤器,这个过滤器名字叫springSecurityFilterChain类型是FilterChainProxy
(二)核心过滤器里面是过滤器链(列表),过滤器链的每个元素都是一组URL对应一组过滤器
(三)WebSecurity用来创建FilterChainProxy过滤器,HttpSecurity用来创建过滤器链的每个元素。
三、使用
特殊说明:以下内容是以本人项目需求为标准配置的spring security,也是基于spring boot框架的。
(一)引入依赖(pom.xml)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
(二)配置
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// 基于token,所以不需要session
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.formLogin()//表单登录
.usernameParameter("mobile")
.passwordParameter("password")
.loginProcessingUrl("/formLogin")
.permitAll()
.successHandler(authenticationSuccessHandler)//登陆成功的处理
.failureHandler(authenticationFailureHandler)//登陆失败的处理
.and()
.authorizeRequests()
.antMatchers(
"/v2/**",//swagger相关工具页面
"/swagger-resources/**",//swagger相关工具页面
"/swagger-ui.html/**"//swagger相关工具页面
)//白名单,不验证,不授权,不防护
.permitAll()//permitALL()表示放开和登陆有关的接口
.anyRequest().authenticated()//除白名单外都需要验证才可访问
.and()
.csrf()
.disable()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler)
.permitAll(false)
.and()
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
;// 自定义的过滤器顺序为:ipFilter -> logFilter -> jwtClientTypeFilter -> tokenFilter -> sendSmsFilter
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
}
1、