文章目录
前言: 坚持不是件容易的事. 距离上次发言已是半载. 最近更新了个人项目的登录权限模块;增加了手机号认证,到此实现了spring security 双重认证方式.目前可以自行注册体验.
一: Spring Boot 引入Security 的 pom依赖
1.1: 首先引入pom jar 包
spring boot使用security 只需引入以下配置,会自动拉取当前boot版本下的security依赖模块:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
当前项目SpringBoot 版本 2.0.4.RELEASE; 引入后可以看到 当前引入了 以下模块版本;spring-security-config;
spring-security-core;spring-security-web;
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
1.2: 配置 WebSecurityConfig
@EnableWebSecurity 作用 :
-
加载了WebSecurityConfiguration配置类, 配置安全认证策略。
在这个配置类中,注入了一个非常重要的bean, bean的name为: springSecurityFilterChain,这是Spring Secuity的核心过滤器, 这是请求的认证入口。 -
加载了AuthenticationConfiguration, 配置了认证信息。
这个类是来配置认证相关的核心类, 这个类的主要作用是,
向spring容器中注入AuthenticationManagerBuilder, AuthenticationManagerBuilder其实是使用了建造者模式,
他能建造AuthenticationManager, 这个类前面提过,是身份认证的入口。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Autowired
private MyAuthenticationEntryPoint myAuthenticationEntryPoint;
@Autowired
private MyAccessDeniedHandler myAccessDeniedHandler;
@Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Autowired
private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
@Autowired
private MyLogoutSuccessHandler myLogoutSuccessHandler;
@Resource
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
// 自定义 账号登录身份认证组件
auth.authenticationProvider(new JwtAuthenticationProvider(userDetailsService));
// 自定义 短信登录身份认证组件
auth.authenticationProvider(new SmsCodeAuthenticationProvider());
}
//各类错误异常处理 以下针对于访问资源路径 认证异常捕获 和 无权限处理
/**
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 项目中用到iframe嵌入网页,然后用到springsecurity就被拦截了 浏览器报错 x-frame-options deny
// 原因是因为springSecurty使用X-Frame-Options防止网页被Frame
http.headers().frameOptions