springboot整合security进行权限校验
时间: 2023-09-06 11:11:59 浏览: 98
Spring Boot是一个快速开发应用程序的框架,Spring Security是一个安全框架,可以对应用程序进行身份验证和授权。在Spring Boot中,可以将Spring Security与应用程序集成,实现对用户身份验证和授权的支持。
以下是在Spring Boot中整合Spring Security进行权限校验的步骤:
1. 添加Spring Security依赖
在build.gradle或pom.xml中添加Spring Security依赖:
```
implementation 'org.springframework.boot:spring-boot-starter-security'
```
2. 创建Spring Security配置类
创建一个继承自WebSecurityConfigurerAdapter的配置类:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and().formLogin()
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login")
.permitAll();
}
}
```
在configure方法中配置Spring Security:
- 配置用户认证,使用UserDetailsService实现类和BCryptPasswordEncoder进行密码加密
- 配置请求授权,指定请求路径需要哪些角色才能访问
- 配置登录页面和登出路径
3. 创建用户实体类和用户认证实现类
创建一个用户实体类和一个实现UserDetailsService接口的用户认证实现类:
```
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "enabled")
private boolean enabled;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
// getters and setters
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
}
```
```
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return user;
}
}
```
4. 创建角色实体类和角色认证实现类
创建一个角色实体类和一个实现GrantedAuthority接口的角色认证实现类:
```
@Entity
@Table(name = "roles")
public class Role implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
// getters and setters
@Override
public String getAuthority() {
return name;
}
}
```
```
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleRepository roleRepository;
@Override
public Role findByName(String name) {
return roleRepository.findByName(name);
}
}
```
5. 创建控制器
创建一个控制器,用于测试权限校验:
```
@RestController
public class TestController {
@GetMapping("/admin")
public String admin() {
return "Hello Admin";
}
@GetMapping("/user")
public String user() {
return "Hello User";
}
}
```
6. 启动应用程序
现在可以启动应用程序并访问控制器中的/admin和/user路径。只有具有相应角色的用户才能访问。
以上是在Spring Boot中整合Spring Security进行权限校验的步骤,希望对你有所帮助。
阅读全文