SpringBoot Security 入门
文章目录
- 初始化
- 自定义用户和密码
- 数据库校验
- 配置类
- 安全认证
- 获取用户信息
初始化
pom 文件添加依赖,SpringBoot 版本 2.7.4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.7.4</version>
</dependency>
添加依赖后,在浏览器请求接口,会弹出登录页面
默认登录账号是:user
密码在运行后台有打印
输入账号密码后,接口可以正常访问,nice,入门了
自定义用户和密码
深入源码可以看到
默认用户名是 user
默认密码是 uuid
所以修改默认用户名和密码也很简单
spring:
security:
user:
name: myname
password: 123
数据库校验
springboot 配置 MYSQL ,参考文章
注意:低版本的 security 使用 WebSecurityConfigurerAdapter 配置,但这个类新版已经被放弃了
配置类
- anyRequest().authenticated():任务静态资源都必须通过校验
- formLogin():开启登录页面进行用户验证
- antMatchers:哪些接口可以不需要权限校验
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
;
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring().antMatchers("/test/**");
}
}
安全认证
实现 AuthenticationProvider 接口
- authenticate():判断用户名密码是否正确
- BadCredentialsException:校验错误的异常类
- UsernamePasswordAuthenticationToken:校验正确时,返回根据用户名、密码、权限生成的 token
- supports:暂无用
- userDetailsService.loadUserByUsername:获取用户信息,然后比较数据库存储的密码和传入的密码是否一致
@Component
@Slf4j
public class SelfAuthenticationProvider implements AuthenticationProvider {
@Resource
SelfUserDetailsService userDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userName = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
log.info("userName:{}, password:{}", userName, password);
if (StringUtils.isBlank(userName)) {
log.error("用户名不能为空");
throw new BadCredentialsException("用户名不能为空");
} else if (StringUtils.isBlank(password)) {
log.error("密码不能为空");
throw new BadCredentialsException("密码不能为空");
}
UserDetails userInfo = userDetailsService.loadUserByUsername(userName);
String myPassword = userInfo.getPassword();
log.info("数据库存的密码:{}",myPassword);
if (!password.equals(myPassword)) {
log.error("用户名密码不正确");
throw new BadCredentialsException("用户名或密码错误");
} else {
return new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
}
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
获取用户信息
继承 UserDetailsService
- IUserMapper :根据用户名查询用户信息
- User:新建用户类,位于 org.springframework.security.core.userdetails
@Service
@Slf4j
public class SelfUserDetailsService implements UserDetailsService {
@Resource
IUserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", username);
UserPO userPO = userMapper.selectOne(queryWrapper);
log.info(" user: {}", userPO);
if (userPO == null) {
throw new BadCredentialsException("没有此用户!");
}
User userInfo = new User(username, userPO.getPassword(), new ArrayList<>());
return userInfo;
}
}