springboot项目怎么做权限控制
时间: 2023-11-03 20:04:17 浏览: 33
在Spring Boot项目中,可以使用Spring Security框架来实现权限控制。
首先,需要在pom.xml中添加Spring Security依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后,在项目中创建一个类继承WebSecurityConfigurerAdapter,并重写configure方法:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
在上面的代码中,我们配置了访问/admin/**路径的请求需要ADMIN角色,/user/**路径的请求需要USER角色,其他请求需要经过身份验证。同时,我们还配置了表单登录和注销功能。
最后,需要实现UserDetailsService接口,用于从数据库或其他数据源中查询用户信息。例如:
```
@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("用户不存在");
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
AuthorityUtils.createAuthorityList(user.getRoles().toArray(new String[0]))
);
}
}
```
在上面的代码中,我们查询了数据库中的用户信息,并将用户的角色作为权限列表返回。
需要注意的是,这里的User是自定义的实体类,包含了用户名、密码和角色等字段。UserRepository则是负责从数据库中查询用户信息的接口。
这样,我们就完成了Spring Boot项目的权限控制。