springsecurity 权限校验使用代码举例
时间: 2023-06-17 19:04:47 浏览: 86
springsecurity例子
4星 · 用户满意度95%
好的,下面给出一个基于Spring Security的权限校验的示例代码:
1. 定义User对象
```
public class User implements UserDetails {
private Long id;
private String username;
private String password;
private List<Role> roles;
// getters and setters
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
@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. 定义Role对象
```
public class Role {
private Long id;
private String name;
// getters and setters
}
```
3. 实现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 user;
}
}
```
4. 配置Spring Security
```
@Configuration
@EnableWebSecurity
public class WebSecurityConfig 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()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
5. 在Controller中使用注解进行权限校验
```
@RestController
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {
// ...
}
@RestController
@RequestMapping("/user")
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public class UserController {
// ...
}
```
以上代码示例中,我们首先定义了一个User对象和一个Role对象,User对象实现了UserDetails接口,并在getAuthorities方法中返回该用户所拥有的权限列表。然后我们实现了UserDetailsService接口,在loadUserByUsername方法中根据用户名从数据库中查询用户信息。接着我们配置了Spring Security,使用HttpSecurity对象进行权限校验的配置,使用AuthenticationManagerBuilder对象配置UserDetailsService,并使用PasswordEncoder对象进行密码加密。最后,在Controller中使用@PreAuthorize注解进行权限校验。
阅读全文