0

There is an Oauth2Authentication object that contains user-authority. When I want to get its authority and set it in authority of User object like this:

OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();

LinkedHashMap linkedHashMap = (LinkedHashMap) oAuth2Authentication.getUserAuthentication().getDetails();


user.setAuthorities((Set<GrantedAuthority>) oAuth2Authentication.getAuthorities());

the following exception is raised:

java.lang.ClassCastException: java.util.Collections$UnmodifiableRandomAccessList cannot be cast to java.util.Set

How do I fix it?

Note:
The type of Authorities of User object is Set<GrantedAuthority>


If oAuth2Authentication.getAuthorities() is a List, you can easily create a Set from it:

user.setAuthorities(new HashSet<GrantedAuthority>(oAuth2Authentication.getAuthorities()));

Note that GrantedAuthority should have a proper implementation of hashCode() and equals() in order to be used as a member of a HashSet.

4

1 回答 1

2

如果oAuth2Authentication.getAuthorities()是 a List,您可以轻松地从中创建 a Set

user.setAuthorities(new HashSet<GrantedAuthority>(oAuth2Authentication.getAuthorities()));

请注意,GrantedAuthority应该正确实现hashCode()andequals()才能用作 a 的成员HashSet

于 2019-03-11T14:13:56.363 回答