jumbojett/openid-connect-php

repository·master·Indexed 20 days ago

https://github.com/jumbojett/openid-connect-php

A PHP library for integrating OpenID Connect authentication into applications. It supports Authorization Code Flow, Implicit Flow, PKCE, and Client Credentials. Key features include automatic provider discovery, dynamic client registration, token introspection (RFC 7662), token revocation (RFC 7009), and back-channel logout handling. Requires PHP 7.2+ with CURL and JSON extensions.

Tokens
5.3K
Snippets
23
Records
24
Agent score
23%

What's inside jumbojett-openid-connect-php

  1. Handle Back-channel Logout

    master

    Back-channel logout allows an OpenID Provider (OP) to notify your Relying Party (RP) to end a session via a POST request.

    To handle this:

    1. Use verifyLogoutToken() to validate the incoming token.
    2. Retrieve the session identifier using getSidFromBackChannel() or the subject using getSubjectFromBackChannel().
    3. Use these identifiers to locate and destroy the corresponding local session in your application (e.g., by looking up a session ID in Redis).
    // Hypothetical implementation of a logout handler
    function handleLogout() {
        if ($this->oidc->verifyLogoutToken()) {
            $sid = $this->oidc->getSidFromBackChannel();
    
            if (isset($sid)) {
                // Example: finding and destroying a session via Redis
                $this->redis->connect('127.0.0.1', 6379);
                $session_id_to_destroy = $this->redis->get($sid);
                if ($session_id_to_destroy) {
                    session_commit();
                    session_id($session_id_to_destroy);
                    session_start();
                    $_SESSION = [];
                }
            }
        }
    }
  2. Implement a Basic OpenID Connect Client

    master

    To authenticate a user through the standard OpenID Connect flow, instantiate OpenIDConnectClient with the provider URL, your Client ID, and Client Secret. Call authenticate() to start the flow and requestUserInfo() to retrieve specific user attributes.

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient('https://id.provider.com',
                                    'ClientIDHere',
                                    'ClientSecretHere');
    $oidc->setCertPath('/path/to/my.cert');
    $oidc->authenticate();
    $name = $oidc->requestUserInfo('given_name');
  3. Install jumbojett/openid-connect-php via Composer

    master

    Install the library using Composer and include the autoloader in your project.

    Requirements:

    • PHP 7.2 or greater
    • CURL extension
    • JSON extension
    composer require jumbojett/openid-connect-php
    require __DIR__ . '/vendor/autoload.php';
  4. Handle JWE (Encrypted JWT) responses

    master

    If the UserInfo endpoint returns a response with Content-Type: application/jwt and the header contains an enc (encryption) field, the client identifies it as a JWE.

    Note: The base OpenIDConnectClient throws an exception for JWEs. To support encrypted responses, you must extend the class and implement the handleJweResponse(string $jwe): string method.

  5. Initialize the OpenIDConnectClient

    master

    To use the client, instantiate OpenIDConnectClient with the provider's URL, your client ID, and your client secret. You can also optionally provide an issuer URL. The client uses the provider URL to perform automatic discovery of the OpenID Connect configuration via the .well-known/openid-configuration endpoint.

    use Jumbojett\OpenIDConnectClient;
    
    $providerUrl = 'https://example.com/.well-known/openid-configuration';
    $clientId = 'your_client_id';
    $clientSecret = 'your_client_secret';
    $issuer = 'https://example.com';
    
    $client = new OpenIDConnectClient($providerUrl, $clientId, $clientSecret, $issuer);
  6. Implement Implicit Flow (e.g., Azure AD B2C)

    master

    For providers requiring the Implicit Flow, configure the client using setResponseTypes(['id_token']), setAllowImplicitFlow(true), and addAuthParam(['response_mode' => 'form_post']). Use getVerifiedClaims() to access the claims.

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient('https://id.provider.com',
                                    'ClientIDHere',
                                    'ClientSecretHere');
    $oidc->setResponseTypes(['id_token']);
    $oidc->setAllowImplicitFlow(true);
    $oidc->addAuthParam(['response_mode' => 'form_post']);
    $oidc->setCertPath('/path/to/my.cert');
    $oidc->authenticate();
    $sub = $oidc->getVerifiedClaims('sub');
  7. Request a Resource Owner Token (with client auth)

    master

    To request a token using a Resource Owner's credentials (username/password) with client authentication, use requestResourceOwnerToken(true). Use addAuthParam() to pass the credentials.

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient('https://id.provider.com',
                                    'ClientIDHere',
                                    'ClientSecretHere');
    $oidc->providerConfigParam(['token_endpoint'=>'https://id.provider.com/connect/token']);
    $oidc->addScope(['my_scope']);
    
    // Add username and password
    $oidc->addAuthParam(['username'=>'<Username>']);
    $oidc->addAuthParam(['password'=>'<Password>']);
    
    // Perform the auth and return the token
    $token = $oidc->requestResourceOwnerToken(TRUE)->access_token;
  8. Implement a PKCE Client

    master

    To use Proof Key for Code Exchange (PKCE), instantiate the client with a null secret and call setCodeChallengeMethod('S256') before calling authenticate().

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient('https://id.provider.com',
                                    'ClientIDHere',
                                    null);
    $oidc->setCodeChallengeMethod('S256');
    $oidc->authenticate();
    $name = $oidc->requestUserInfo('given_name');
  9. Perform Dynamic Registration

    master

    If your provider supports it, you can use the register() method to dynamically register your client. You must then retrieve and store the generated ClientID and ClientSecret using getClientID() and getClientSecret().

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient("https://id.provider.com");
    
    $oidc->register();
    $client_id = $oidc->getClientID();
    $client_secret = $oidc->getClientSecret();
    
    // Be sure to add logic to store the client id and client secret
  10. Request a Client Credentials Token

    master

    To obtain an access token using the Client Credentials flow, use requestClientCredentialsToken(). You may need to manually set the token_endpoint via providerConfigParam() and define scopes using addScope().

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient('https://id.provider.com',
                                    'ClientIDHere',
                                    'ClientSecretHere');
    $oidc->providerConfigParam(['token_endpoint'=>'https://id.provider.com/connect/token']);
    $oidc->addScope(['my_scope']);
    
    // Access the token from the returned object
    $clientCredentialsToken = $oidc->requestClientCredentialsToken()->access_token;
  11. Configure Network and Security settings

    master

    You can customize the network behavior and security certificates of the client using the following methods:

    • setHttpProxy(string $proxyUrl): Configure a proxy server.
    • setCertPath(string $path): Specify a path to a certificate file.
    • setVerifyHost(bool $verify): Disable SSL host verification (use only for development).
    • setVerifyPeer(bool $verify): Disable SSL peer verification (use only for development).
    • setHttpUpgradeInsecureRequests(bool $upgrade): Disable upgrading to HTTPS if your local system does not support it.
    // Configure a proxy
    $oidc->setHttpProxy("http://my.proxy.com:80/");
    
    // Configure a cert
    $oidc->setCertPath("/path/to/my.cert");
    
    // Development only: disable SSL security
    $oidc->setVerifyHost(false);
    $oidc->setVerifyPeer(false);
    
    // Disable HTTPS upgrade
    $oidc->setHttpUpgradeInsecureRequests(false);
  12. Introspect an Access Token

    master

    Use introspectToken(string $token) to check the validity of an access token according to RFC 7662. The returned object contains an active property.

    use Jumbojett\OpenIDConnectClient;
    
    $oidc = new OpenIDConnectClient('https://id.provider.com',
                                    'ClientIDHere',
                                    'ClientSecretHere');
    $data = $oidc->introspectToken('an.access-token.as.given');
    if (!$data->active) {
        // the token is no longer usable
    }