SpringSecurity相关
- 一、SpringSecurity简介
- 二、SpringSecurity主要功能
- 三、SpringSecurity的Maven依赖
- 四、Security本质:过滤器链
- 五、用户认证
- 1、根据用户实体,封装一个UserDetails实体对象LoginUser类
- 2、自定义UserDetailsService接口的实现
一、SpringSecurity简介
安全管理框架
二、SpringSecurity主要功能
- 认证: 用户认证(依赖jwt的token)
- 授权: 经过认证后,判断用户是否有权限进行某个操作
三、SpringSecurity的Maven依赖
SpringBoot 里面有具体启动器,所以不需要指明版本号
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
四、Security本质:过滤器链
debugger查看run容器
五、用户认证
1、根据用户实体,封装一个UserDetails实体对象LoginUser类
package com.zhw.domain.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
private Admin admin;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return admin.getPassword();
}
@Override
public String getUsername() {
return admin.getUserName();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
2、自定义UserDetailsService接口的实现
package com.zhw.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhw.domain.entity.Admin;
import com.zhw.domain.entity.LoginUser;
import com.zhw.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Service
@SuppressWarnings("all")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private AdminMapper adminMapper;
@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
// 根据用户名查询用户信息
LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Admin::getUserName, username);
Admin admin = adminMapper.selectOne(queryWrapper);
// 判断是否查到用户 如果没查到抛出异常
if (Objects.isNull(admin)) {
throw new RuntimeException("用户不存在");
}
// 返回用户信息
// TODO 查询权限信息封装【授权功能】
return new LoginUser(admin);
}
}