All Downloads are FREE. Search and download functionalities are using the official Maven repository.

momento.sdk.AuthTokenParser Maven / Gradle / Ivy

There is a newer version: 1.17.0
Show newest version
package momento.sdk;

import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import java.util.Optional;
import momento.sdk.exceptions.InvalidArgumentException;

final class AuthTokenParser {

  private AuthTokenParser() {}

  static Claims parse(String authToken) {
    try {
      ensurePresent(authToken);
      Jwt parsed =
          Jwts.parserBuilder().build().parseClaimsJwt(tokenWithOnlyHeaderAndClaims(authToken));
      return new Claims(parsed.getBody());
    } catch (Exception e) {
      throw new InvalidArgumentException("Failed to parse Auth Token", e);
    }
  }

  private static void ensurePresent(String authToken) {
    if (authToken == null || authToken.isEmpty()) {
      throw new InvalidArgumentException("Malformed Auth Token.");
    }
  }

  // https://github.com/jwtk/jjwt/issues/280
  private static String tokenWithOnlyHeaderAndClaims(String authToken) {
    String[] splitToken = authToken.split("\\.");
    if (splitToken == null || splitToken.length < 2) {
      throw new InvalidArgumentException("Malformed Auth Token");
    }
    return splitToken[0] + "." + splitToken[1] + ".";
  }

  static class Claims {

    private static final String CONTROL_ENDPOINT_CLAIM_NAME = "cp";
    private static final String CACHE_ENDPOINT_CLAIM_NAME = "c";

    private Optional controlEndpoint;
    private Optional cacheEndpoint;

    private Claims(io.jsonwebtoken.Claims claims) {
      controlEndpoint =
          Optional.ofNullable((String) claims.getOrDefault(CONTROL_ENDPOINT_CLAIM_NAME, null));
      cacheEndpoint =
          Optional.ofNullable((String) claims.getOrDefault(CACHE_ENDPOINT_CLAIM_NAME, null));
    }

    Optional controlEndpoint() {
      return controlEndpoint;
    }

    Optional cacheEndpoint() {
      return cacheEndpoint;
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy