Spring Security
概述:
正如你可能知道的关于安全方面的两个主要区域是“认证”和“授权”(或者访问控制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分,这两点也是 Spring Security 重要核心功能。
- (1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问
该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认
证过程。通俗点说就是系统认为用户是否能登录 - (2)用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户
所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以
进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的
权限。通俗点讲就是系统判断用户是否有权限去做某些事情。
基本原理
SpringSecurity 本质是一个过滤器链:
从启动是可以获取到过滤器链:
- org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
- org.springframework.security.web.context.SecurityContextPersistenceFilter
- org.springframework.security.web.header.HeaderWriterFilter
- org.springframework.security.web.csrf.CsrfFilter
- org.springframework.security.web.authentication.logout.LogoutFilter
- org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
- org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
- org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
- org.springframework.security.web.savedrequest.RequestCacheAwareFilter
- org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
- org.springframework.security.web.authentication.AnonymousAuthenticationFilter
- org.springframework.security.web.session.SessionManagementFilter
- org.springframework.security.web.access.ExceptionTranslationFilter
- org.springframework.security.web.access.intercept.FilterSecurityInterceptor
UserDetailsService 接口讲解
当什么也没有配置的时候,账号和密码是由 Spring Security 定义生成的。而在实际项目中账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑。如果需要自定义逻辑时,只需要实现 UserDetailsService 接口即可。接口定义如下:
public class MyUserDetailService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return null;
}
}
-
返回值 UserDetails
这个类是系统默认的用户“主体” -
参数讲解
// 表示获取登录用户所有权限 Collection<? extends GrantedAuthority> getAuthorities(); // 表示获取密码 String getPassword(); // 表示获取用户名 String getUsername(); // 表示判断账户是否过期 boolean isAccountNonExpired(); // 表示判断账户是否被锁定 boolean isAccountNonLocked(); // 表示凭证{密码}是否过期 boolean isCredentialsNonExpired(); // 表示当前用户是否可用 boolean isEnabled();
我们只需要使用 User 这个实现类类即可
/**
* Calls the more complex constructor with all boolean arguments set to {@code true}.
*/
public User(String username, String password, Collection<? extends GrantedAuthority> authorities) {
this(username, password, true, true, true, true, authorities);
}
**注:**方法参数 username表示用户名。此值是客户端表单传递过来的数据。默认情况下必须叫 username,否则无法接收。
PasswordEncoder 接口讲解
// 表示把参数按照特定的解析规则进行解析
String encode(CharSequence rawPassword);
// 表示验证从存储中获取的编码密码与编码后提交的原始密码是否匹配。如果密码匹
配,则返回 true;如果不匹配,则返回 false。第一个参数表示需要被解析的密码。第二个
参数表示存储的密码。
boolean matches(CharSequence rawPassword, String encodedPassword);
// 表示如果解析的密码能够再次进行解析且达到更安全的结果则返回 true,否则返回
false。默认返回 false。
default boolean upgradeEncoding(String encodedPassword) {
return false;
}
实现类
BCryptPasswordEncoder 是 Spring Security 官方推荐的密码解析器,平时多使用这个解析器。BCryptPasswordEncoder 是对 bcrypt 强散列方法的具体实现。是基于 Hash 算法实现的单向加密。可以通过 strength 控制加密强度,默认 10.
/**
* 测试BCryptPassword
*/
@Test
public void testBCryptPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String wss8752 = encoder.encode("wss8752");
System.out.println(wss8752);
System.out.println(encoder.matches("wss8752", wss8752));
}
SpringSecurity Web 权限方案
- 在配置文件中
application.yml
spring:
security:
user:
name: wss
password: wss8752
- 编写类实现接口
编写实现类实现WebSecurityConfigurerAdapter
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 表单登录
http.formLogin()
.and()
// 认证配置
.authorizeHttpRequests()
// 任何请求
.anyRequest()
// 需要身份验证
.authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Service层
@Service
public class UserService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 判断用户名是否存在
if (!"admin".equals(username)) {
throw new UsernameNotFoundException("用户名不存在!");
}
// 从数据库中获取的密码 wss8752 的密文
String pwd = "$2a$10$p93V1CfE5rCG4MhRLCdbs.m1jxrRa.0RgTm93IXcYiAA6hcSr2zbi";
// 第三个参数表示权限
return new User(username, pwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,"));
}
}