| 12345678910111213141516171819202122232425262728293031323334353637 |
- 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<Jwt, Collection<GrantedAuthority>>{
- @Override
- public Collection<GrantedAuthority> convert(Jwt jwt) {
- final Map<String, List<String>> realmAccess = (Map<String, List<String>>) jwt.getClaims().get("realm_access");
- List<GrantedAuthority> realmList = realmAccess.get("roles")
- .stream()
- .map(roleName -> roleName)
- .map(SimpleGrantedAuthority::new)
- .collect(Collectors.toList());
- final Map<String, List<String>> resourceAccess = (Map<String, List<String>>) jwt.getClaims().get("resource_access");
- ObjectMapper mapper = new ObjectMapper();
- JsonNode token = mapper.convertValue(resourceAccess, JsonNode.class);
- Set<String> rolesWithPrefix = new HashSet<>();
- token.elements()
- .forEachRemaining(e -> e.path("roles")
- .elements()
- .forEachRemaining(r -> rolesWithPrefix.add(r.asText())));
- final List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(rolesWithPrefix.toArray(new String[0]));
- realmList.addAll(authorityList);
- return realmList;
- }
- }
|