基于spring boot的spring security的权限系统的设计
以下是一个简化的Spring Security权限系统设计示例,包括用户实体、角色实体和权限实体。
// 用户实体
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// 用户拥有多个角色
@ManyToMany(cascade = CascadeType.ALL)
private Collection<Role> roles;
// 省略getter和setter
}
// 角色实体
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// 角色拥有多个权限
@ManyToMany(cascade = CascadeType.ALL)
private Collection<Permission> permissions;
// 省略getter和setter
}
// 权限实体
@Entity
public class Permission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// 省略getter和setter
}
// Spring Security配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// 其他配置...
}
// UserDetailsService实现
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found."));
List<GrantedAuthority> authorities = user.getRoles()
.stream()
.flatMap(role -> role.getPermissions().stream())
.map(permission -> new SimpleGrantedAuthority(permission.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
authorities
);
}
}
在这个例子中,我们定义了用户、角色和权限实体,并通过UserDetailsService
自定义了用户认证逻辑。在CustomUserDetailsService
中,我们查询用户,并将用户的角色权限转换为Spring Security可以识别的GrantedAuthority
集合。这样,Spring Security就可以使用这些权限来控制
评论已关闭