package com.inspur.smsb.gateway.config; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import java.util.*; import java.util.stream.Collectors; public class RealmRoleConverter implements Converter>{ @Override public Collection convert(Jwt jwt) { final Map> realmAccess = (Map>) jwt.getClaims().get("realm_access"); List realmList = realmAccess.get("roles") .stream() .map(roleName -> roleName) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); final Map> resourceAccess = (Map>) jwt.getClaims().get("resource_access"); ObjectMapper mapper = new ObjectMapper(); JsonNode token = mapper.convertValue(resourceAccess, JsonNode.class); Set rolesWithPrefix = new HashSet<>(); token.elements() .forEachRemaining(e -> e.path("roles") .elements() .forEachRemaining(r -> rolesWithPrefix.add(r.asText()))); final List authorityList = AuthorityUtils.createAuthorityList(rolesWithPrefix.toArray(new String[0])); realmList.addAll(authorityList); return realmList; } }