二十、Spring Boot 安全管理(Spring Security)
(一)、介绍
Spring Security是Spring 官方提供的一个高度自定义的安全框架,是一种基于 Spring AOP 和 Servlet 过滤器的安全框架。
提供了声明式安全访问控制功能,减少了为系统安全而编写大量重复代码的工作。主要包含“认证”和“授权”(或者访问控制)两个核心功能。
(二)、简单使用
1.创建Spring Boot项目
2.添加依赖
修改pox.xml文件。添加spring security相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.启动项目测试
注:
- 默认登录账号为user,登录密码会打印在控制台;
- 默认账号信息可以通过项目配置文件(application.properties)修改:
spring.security.user.name=user
spring.security.user.password=password
(三)、自定义配置
1、用户信息实体类
- 创建用户信息实体类
- 实现接口
UserDetails
- 实现接口方法
// 用户名
String getUsername();
// 用户密码
String getPassword();
// 获取用户权限
Collection<? extends GrantedAuthority> getAuthorities();
// 账户是否过期
boolean isAccountNonExpired();
// 账号是否锁定
boolean isAccountNonLocked();
// 凭证(密码)是否过期
boolean isCredentialsNonExpired();
// 账号是否启用
boolean isEnabled();
注:在进行账号验证时只有 isAccountNonExpired()、isAccountNonLocked()、isCredentialsNonExpired()、isEnabled() 这四项都为true时才能通过验证(没有这几个属性可以都设置默认返回true)。
2、创建配置文件
- 新建类继承抽象类
WebSecurityConfigurerAdapter
并添加注解@Configuration
; - 重写
configure
方法,编写自定义登录信息认证逻辑。
示列代码:
package com.ikaros.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.PrintWriter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 配置认证
http.formLogin()
// 哪个URL为登录页面
// .loginPage("/login")
// 当发现什么URL时执行登录逻辑
.loginProcessingUrl("/login")
// 登录参数
.usernameParameter("username")
.passwordParameter("password")
// 成功后跳转到哪里
.successHandler(
(httpServletRequest, httpServletResponse, authentication) -> {
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
out.write("{\"status\":\"success\",\"msg\":\"登录成功\"}");
out.flush();
out.close();
})
// 失败后跳转到哪里
.failureHandler(
(httpServletRequest, httpServletResponse, e) -> {
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
out.write("{\"status\":\"error\",\"msg\":\"登录失败,"+ e.getMessage()+"\"}");
out.flush();
out.close();
});
// 设置URL的授权问题
// 多个条件取交集
http.authorizeRequests()
// 匹配 / 控制器 permitAll() 不需要被认证就可以访问
// .antMatchers("/swagger**/**").permitAll()
// anyRequest() 所有请求 authenticated() 必须被认证
.anyRequest().authenticated();
// 关闭csrf,禁用跨站伪造
http.csrf().disable();
}
@Override
public void configure(WebSecurity web) {
// 无需验证接口
web.ignoring().antMatchers(
"/swagger**/**",
"/webjars/**",
"/v3/**",
"/doc.html");
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
3、其它配置
(1)记住我配置
- 前端配置
前端请求参数需要包含参数remember-me
且值为true
。 - security 配置
...
user表访问接口:
private final UserServiceImpl userServiceImpl;
数据源配置:
private final javax.sql.DataSource.DataSource dataSource;
...
...
记住我配置:
// 记住我
http
.rememberMe()
// 设置userDetailsService
.userDetailsService(userServiceImpl)
// 设置数据访问层
.tokenRepository(persistentTokenRepository())
// 记住我的时间(秒),24小时
.tokenValiditySeconds(60 * 60 * 24)
;
...
数据访问:
/**
* 持久化token
*
* Security中,默认是使用PersistentTokenRepository的子类InMemoryTokenRepositoryImpl,将token放在内存中
* 如果使用JdbcTokenRepositoryImpl,会创建表persistent_logins,将token持久化到数据库
* @return PersistentTokenRepository
*/
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
// 设置数据源
tokenRepository.setDataSource(dataSource);
// 启动创建表,创建成功后需要注释掉
tokenRepository.setCreateTableOnStartup(true);
return tokenRepository;
}
(四)、配置详解
1.configure方法
protected void configure(AuthenticationManagerBuilder auth) throws Exception {}
public void configure(WebSecurity web) throws Exception {}
protected void configure(HttpSecurity httpSecurity) throws Exception {}
AuthenticationManagerBuilder
:用于配置全局认证相关的信息,就是UserDetailsService和AuthenticationProviderWebSecurity
:用于全局请求忽略规则配置,比如一些静态文件,注册登录页面的放行。HttpSecurity
用于具体的权限控制规则配置,我们这里只需要重写这个方法就可以了
2.HttpSecurity 常用方法
- HttpSecurity 一些常用方法
方法 | 说明 |
---|---|
formLogin() | 开启表单的身份验证 |
loginPage() | 指定登录页面 |
successForwardUrl() | 指定登录成功之后跳转的页面 |
successHandler() | 登录成功后的擦操作逻辑 |
failureForwardUrl() | 指定登录失败之后跳转的页面 |
failureHandler() | 登录失败后的操作逻辑 |
authorizeRequests() | 开启使用HttpServletRequest请求的访问限制 |
oauth2Login() | 开启oauth2 验证 |
rememberMe() | 开启记住我的验证(使用cookie) |
addFilter() | 添加自定义过滤器 |
csrf() | 开启csrf支持 |
登录成功/失败 后的操作逻辑
.successHandler(
(httpServletRequest, httpServletResponse, authentication) -> {
httpServletResponse.sendRedirect("/index")
})
.failureHandler(
(httpServletRequest, httpServletResponse, authentication) -> {
httpServletResponse.sendRedirect("/failure")
})
- 一些认证方法
(五)、相关问题
1.跨域
跨域配置:
- 允许跨域
...
// 跨域
http
.cors()
//禁用跨站伪造
.and().csrf().disable();
...
- 配置跨域(添加Bean)
/**
* 跨域处理
* @return ..
*/
@Bean
CorsConfigurationSource corsConfigurationSource(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration = new CorsConfiguration();
// 允许携带凭证
configuration.setAllowCredentials(true);
// 允许从所有站点跨域
configuration.addAllowedOriginPattern("*");
// 允许所有方法
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(Duration.ofHours(1));
// 对所有URL生效
source.registerCorsConfiguration("/**",configuration);
return source;
}
2.凭证
前端发送请求登录,登录成功后。再次发送请求访问后端接口,需要携带请求参数需要携带凭证信息(cookie信息),否则会没有凭证访问接口,自动重定向到登录页面(默认:/login)导致出现 302 错误。
axios配置:
// 携带凭证信息
axios.defaults.withCredentials = true;