在Spring Security中,重复的grantedAuthorities会被移除。

huangapple go评论89阅读模式
英文:

Duplicate grantedAuthorities are removed in spring security

问题

我正在使用 Spring Boot、AngularJS 和 JPA 编写一个用户管理系统,所有用户功能将分配给 grantedauthorities,然后将其发送回 AngularJS 进行首页设计,但尽管我将权限分配给了 ArrayList 而不是 HashSet,重复的功能仍然被移除。

在循环结束时,grantedauthorities 的大小为12,一切正常,但在返回响应时,重复的功能被移除。

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

   @Autowired
   private UserJpaRepository userJpaRepository;

   @Autowired
   private RoleFeaturesJpaRepository roleFeaturesJpaRepository;

   @Override
   @Transactional
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException  {

      User user = userJpaRepository.findByUsername(username);
      if (user == null) {
         throw new UsernameNotFoundException(
                    "Opps! user not found with user-name: " + username);
      }

      return new org.springframework.security.core.userdetails.User(
         user.getUsername(), user.getPassword(),
         getAuthorities(user)
      );
   }

   private Collection<GrantedAuthority> getAuthorities(User user) {
         
      ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
      Role role = user.getRoles();
      for (Features features : role.getFeatures()){
          RoleFeaturesPK roleFeaturesPK = new RoleFeaturesPK();
          roleFeaturesPK.setRoleId(role.getId());
          roleFeaturesPK.setFeatureId(features.getId());
          Optional<RoleFeatures> roleFeatures = roleFeaturesJpaRepository.findById(roleFeaturesPK);
          RoleFeatures features_entity = roleFeatures.get();
          grantedAuthorities.add(new SimpleGrantedAuthority(features.getName()));
          grantedAuthorities.add(new SimpleGrantedAuthority(features_entity.getReadOption()));
          grantedAuthorities.add(new SimpleGrantedAuthority(features_entity.getReadWriteOption()));

      }
      return grantedAuthorities;
   }
}
英文:

I am writing a user management system with spring boot, angularjs, jpa, ... all the user's features will be assigned to grantedauthorities and will send back to angularjs to design the home page accordingly but even though I am assigning the authorities to ArrayList and not HashSet, still duplicate features are removed.

Size of grantedauthorities is 12 at the end of loop and everything is fine but when it return the response, duplicates are removed.

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

   @Autowired
   private UserJpaRepository userJpaRepository;

   @Autowired
   private RoleFeaturesJpaRepository roleFeaturesJpaRepository;

   @Override
   @Transactional
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException  {

      User user = userJpaRepository.findByUsername(username);
      if (user == null) {
         throw new UsernameNotFoundException(
                    &quot;Opps! user not found with user-name: &quot; + username);
      }

      return new org.springframework.security.core.userdetails.User(
         user.getUsername(), user.getPassword(),
         getAuthorities(user)
      );
   }

   private Collection&lt;GrantedAuthority&gt; getAuthorities(User user) {
         
      ArrayList&lt;GrantedAuthority&gt; grantedAuthorities = new ArrayList&lt;&gt;();
      Role role = user.getRoles();
      for (Features features : role.getFeatures()){
          RoleFeaturesPK roleFeaturesPK = new RoleFeaturesPK();
          roleFeaturesPK.setRoleId(role.getId());
          roleFeaturesPK.setFeatureId(features.getId());
          Optional&lt;RoleFeatures&gt; roleFeatures = roleFeaturesJpaRepository.findById(roleFeaturesPK);
          RoleFeatures features_entity = roleFeatures.get();
          grantedAuthorities.add(new SimpleGrantedAuthority(features.getName()));
          grantedAuthorities.add(new SimpleGrantedAuthority(features_entity.getReadOption()));
          grantedAuthorities.add(new SimpleGrantedAuthority(features_entity.getReadWriteOption()));

      }
      return grantedAuthorities;
   }
}

答案1

得分: 1

以下是您要翻译的内容:

Spring 在使用传递的权限集合创建用户时,会根据以下构造指令从传递的权限集合中移除重复的 GrantedAuthorities:

this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));

sortAuthorities 方法会基于以下比较器对权限进行排序,排序结果不会包含重复项:

private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    public int compare(GrantedAuthority g1, GrantedAuthority g2) {
        // 由于在添加到集合之前会检查每个条目,因此两者都不应为 null。
        // 如果权限为 null,则它是自定义权限,应优先于其他权限。
        if (g2.getAuthority() == null) {
            return -1;
        }

        if (g1.getAuthority() == null) {
            return 1;
        }

        return g1.getAuthority().compareTo(g2.getAuthority());
    }
}
英文:

Duplicated GrantedAuthorities are removed by Spring when creating the User with this instruction from the passed authorities collection in the constructor :

    this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));

sortAuthorities will sort the authorities based on this comparator and the result will not contain duplications :

    	private static class AuthorityComparator implements Comparator&lt;GrantedAuthority&gt;,Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
// Neither should ever be null as each entry is checked before adding it to
// the set.
// If the authority is null, it is a custom authority and should precede
// others.
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
}

答案2

得分: 0

method getAuthorities看起来是没问题的在返回行被移除了
       
private Collection<GrantedAuthority> getAuthorities(User user)
       
  return new org.springframework.security.core.userdetails.User(
     user.getUsername(), user.getPassword(),
      getAuthorities(user)
       
  );
英文:
 method getAuthorities seems ok, it is getting removed on return line maybe
private Collection&lt;GrantedAuthority&gt; getAuthorities(User user) 
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(),
getAuthorities(user)
);

huangapple
  • 本文由 发表于 2020年9月21日 04:14:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63983255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定