https://top234.top/blog/21041107.html
1 启用Spring Security
1.1 添加spring-boot-starter-security依赖
<!-- spring security 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2 配置Spring Security
2.1 基于配置文件的用户存储
# 在配置文件中设置用户名密码
spring:
security:
user:
name: lisi
password: lisi
2.2 基于内存的用户存储
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 设置用户名密码到内存中
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("zs").password(new BCryptPasswordEncoder()
.encode("ls"))
.roles("admin");
}
}
2.3 自定义用户认证
- 创建配置类,指定UserDetailsService接口实现类实例,并注入用户密码的转码方式
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService myUserDetailsService;
/**
* 配置用户密码转码器
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//配置自定义UserDetailsService接口实现类对象并将用户密码转码器注入到用户详情服务中
auth.userDetailsService(myUserDetailsService)
.passwordEncoder(passwordEncoder());
}
}
- 编写UserDetailsService接口实现类,实现loadUserByUsername(String username)方法,自定义用户数据查询方式
package top.top234.springsecurity.service;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List<GrantedAuthority> role = AuthorityUtils.
commaSeparatedStringToAuthorityList("role");
return new User("lisi", new BCryptPasswordEncoder().encode("lisi"), role);
}
}
2.4 自定义用户认证并结合数据库
- 实体类及数据表
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
private String password;
private String role;
}
- dao
package top.top234.springsecurity.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import top.top234.springsecurity.entity.User;
public interface UserRepository extends JpaRepository<User,Integer> {
User findByUsername(String username);
}
- 创建配置类,设置使用哪个UserDetailsService实现类及密码的加密方式
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService myUserDetailsService;
/**
* 配置用户密码转码器
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(myUserDetailsService)//配置自定义UserDetailsService接口实现类实例
.passwordEncoder(passwordEncoder());//将用户密码转码器注入到用户详情服务中
}
}
- 编写UserDetailsService接口实现类,实现loadUserByUsername(String username)方法,自定义用户数据查询方式
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//自定义用户数据查询规则
User user = userRepository.findByUsername(s);
//用户名不存在时抛出org.springframework.security.core.userdetails.UsernameNotFoundException异常
if (user==null){
throw new UsernameNotFoundException("用户名不存在");
}
//将用户role字段转为集合,commaSeparatedStringToAuthorityList()方法参数为字符串,会将字符串参数按照逗号分割为权限集合
List<GrantedAuthority> role = AuthorityUtils
.commaSeparatedStringToAuthorityList(user.getRole());
//方法返回UserDetails接口的实现类对象,UserDetails对象包括有用户名 密码 及 操作权限集合
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(), role);
}
}
3 权限控制 - 保护web请求
3.1 使用自定义登录页面
- 修改SecurityConfig配置类,配置自定义登录页面的路径
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService myUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
/**
* 自定义登录页面配置及设置请求权限
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login")//自定义的登录页面
.loginProcessingUrl("/user/login")//登录访问路径(登录页表单的提交路径),随便填写,由springboot实现