RealmRoleConverter.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package com.inspur.smsb.gateway.config;
  2. import com.fasterxml.jackson.databind.JsonNode;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.springframework.core.convert.converter.Converter;
  5. import org.springframework.security.core.GrantedAuthority;
  6. import org.springframework.security.core.authority.AuthorityUtils;
  7. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import org.springframework.security.oauth2.jwt.Jwt;
  9. import java.util.*;
  10. import java.util.stream.Collectors;
  11. public class RealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>>{
  12. @Override
  13. public Collection<GrantedAuthority> convert(Jwt jwt) {
  14. final Map<String, List<String>> realmAccess = (Map<String, List<String>>) jwt.getClaims().get("realm_access");
  15. List<GrantedAuthority> realmList = realmAccess.get("roles")
  16. .stream()
  17. .map(roleName -> roleName)
  18. .map(SimpleGrantedAuthority::new)
  19. .collect(Collectors.toList());
  20. final Map<String, List<String>> resourceAccess = (Map<String, List<String>>) jwt.getClaims().get("resource_access");
  21. ObjectMapper mapper = new ObjectMapper();
  22. JsonNode token = mapper.convertValue(resourceAccess, JsonNode.class);
  23. Set<String> rolesWithPrefix = new HashSet<>();
  24. token.elements()
  25. .forEachRemaining(e -> e.path("roles")
  26. .elements()
  27. .forEachRemaining(r -> rolesWithPrefix.add(r.asText())));
  28. final List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(rolesWithPrefix.toArray(new String[0]));
  29. realmList.addAll(authorityList);
  30. return realmList;
  31. }
  32. }