RoleSupport.java

  1. package no.nav.data.common.security;

  2. import lombok.RequiredArgsConstructor;
  3. import lombok.extern.slf4j.Slf4j;
  4. import no.nav.data.common.security.dto.AppRole;
  5. import org.springframework.security.core.GrantedAuthority;
  6. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  7. import org.springframework.stereotype.Service;

  8. import java.util.List;
  9. import java.util.Objects;
  10. import java.util.Set;
  11. import java.util.stream.Collectors;

  12. import static no.nav.data.common.security.dto.AppRole.ROLE_PREFIX;
  13. import static no.nav.data.common.utils.StreamUtils.convert;

  14. @Slf4j
  15. @Service
  16. @RequiredArgsConstructor
  17. public class RoleSupport {

  18.     private final SecurityProperties securityProperties;

  19.     public Set<GrantedAuthority> lookupGrantedAuthorities(List<String> groupIds) {
  20.         Set<GrantedAuthority> roles = groupIds.stream()
  21.                 .map(this::roleFor)
  22.                 .filter(Objects::nonNull)
  23.                 .map(this::convertAuthority)
  24.                 .collect(Collectors.toSet());
  25.         roles.add(convertAuthority(AppRole.READ.name()));
  26.         log.trace("roles {}", convert(roles, GrantedAuthority::getAuthority));
  27.         return roles;
  28.     }

  29.     /**
  30.      * token v2 does not allow us to fetch group details, so we have to map by id instead
  31.      */
  32.     private String roleFor(String group) {
  33.         if (securityProperties.getAdminGroups().contains(group)) {
  34.             return AppRole.ADMIN.name();
  35.         }
  36.         // for future - add team -> system roles here

  37.         // temporarily give WRITE access to everyone with a valid token
  38.         return AppRole.WRITE.name();
  39.     }

  40.     private GrantedAuthority convertAuthority(String role) {
  41.         return new SimpleGrantedAuthority(ROLE_PREFIX + role);
  42.     }

  43. }