Skip to content

Consider adding a JWKS retriever helper #610

@chx

Description

@chx

I am using the helper below but integrating this with decode would avoid decoding twice:

  protected static function getJwks(string $token): array {
    [, $claims_encoded] = explode('.', $token);
    if (!$claims_json = JWT::urlsafeB64Decode($claims_encoded)) {
      throw new \InvalidArgumentException("Unable to decode JWT token claims $claims_encoded");
    }
    if (!$claims = JWT::jsonDecode($claims_json)) {
      throw new \InvalidArgumentException("JWT token claims is invalid JSON $claims_json");
    }
    if (!isset($claims->iss)) {
      throw new \InvalidArgumentException(\sprintf("JWT token claims do not contain issuer $claims_json"));
    }
    $url = $claims->iss . "/.well-known/openid-configuration";
    if (!$configuration_json = @file_get_contents($url)) {
      throw new \LogicException("Unable to read OpenID issuer configuration from $url");
    }
    if (!$configuration = @json_decode($configuration_json, TRUE)) {
      throw new \LogicException("Unable to parse OpenID issuer configuration $configuration_json");
    }
    if (!isset($configuration['jwks_uri'])) {
      throw new \LogicException("OpenID issuer configuration does not contain jwks_uri $configuration_json");
    }
    $jwks_uri = $configuration['jwks_uri'];
    if (!$keys_json = @file_get_contents($jwks_uri)) {
      throw new \LogicException("Unable to read OpenID keys from $jwks_uri");
    }
    if (!$keys = @json_decode($keys_json, TRUE)) {
      throw new \LogicException("Unable to parse OpenID keys $keys_json");
    }
    return JWK::parseKeySet($keys);
  }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions