【问题标题】:custom role and permissions for every user每个用户的自定义角色和权限
【发布时间】:2018-03-26 10:10:07
【问题描述】:

假设我们有一个用户 A 和一个用户 B

用户 A 具有 ROLE_USER 角色和读写和更新权限

用户 B 也有角色 ROLE_USER 但只能读取权限

有可能吗?以及如何?

以及如何在 spring 安全对象“grantAuthority”中获取权限表和角色

我正在使用 Spring Boot,我的课程扩展了 WebSecurityConfigurerAdapter

【问题讨论】:

    标签: spring hibernate spring-boot spring-security


    【解决方案1】:

    要实现自定义角色,您可以实现自己的“UserDetailsS​​ervice”。 Spring Security UserDetailsService

    这里有一个例子:

    @Service
    public class UsuarioDetailsServiceImp implements UserDetailsService {
    
      @Autowired
      private UsuarioRepository usuarioRepository;
    
      @Override
      public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
          if(email==null||email.isEmpty()){
              throw new UsernameNotFoundException("");
          }
    
          Usuario usuario = usuarioRepository.findByEmail(email);
          if(usuario==null){
              throw new UsernameNotFoundException("");
          }
          List<GrantedAuthority> authorities = new ArrayList<>();
          authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
          if(usuario.isAdmin()){
              authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
          }
          return new User(email,usuario.getPassword(),authorities);
      }
    }
    

    Custom role based auth example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2021-11-26
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多