如何在java中将UnmodifiableRandomAccessList设置为Set

问题描述 投票:0回答:1

有一个包含用户权限的Oauth2Authentication对象。当我想获得它的权限并将其设置为User对象的权限时,如下所示:

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

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


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

引发以下异常:

java.lang.ClassCastException:java.util.Collections $ UnmodifiableRandomAccessList无法强制转换为java.util.Set

我如何解决它?

注意: 用户对象的权限类型是Set<GrantedAuthority>

java spring-security oauth-2.0 spring-security-oauth2 unmodifiable
1个回答
2
投票

如果oAuth2Authentication.getAuthorities()List,你可以轻松地从它创建一个Set

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

请注意,GrantedAuthority应该正确实现hashCode()equals(),以便用作HashSet的成员。

© www.soinside.com 2019 - 2024. All rights reserved.