Credential.java

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

  2. import lombok.Value;
  3. import no.nav.data.common.security.domain.Auth;
  4. import org.springframework.security.core.Authentication;
  5. import org.springframework.security.core.context.SecurityContextHolder;

  6. import java.util.Optional;

  7. @Value
  8. public class Credential {

  9.     String accessToken;
  10.     Auth auth;

  11.     public Credential(String accessToken, Auth auth) {
  12.         this.accessToken = accessToken;
  13.         this.auth = auth;
  14.     }

  15.     public Credential(String accessToken) {
  16.         this(accessToken, null);
  17.     }

  18.     public Credential(Auth auth) {
  19.         this(null, auth);
  20.     }

  21.     public boolean hasAuth() {
  22.         return auth != null;
  23.     }

  24.     public String getAccessToken() {
  25.         return hasAuth() ? auth.getAccessToken() : accessToken;
  26.     }

  27.     public static Optional<Credential> getCredential() {
  28.         return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
  29.                 .filter(Authentication::isAuthenticated)
  30.                 .map(authentication -> authentication.getCredentials() instanceof Credential c ? c : null);
  31.     }
  32. }