PHP OpenID Connect Basic Client

Overview

PHP OpenID Connect Basic Client

A simple library that allows an application to authenticate a user through the basic OpenID Connect flow. This library hopes to encourage OpenID Connect use by making it simple enough for a developer with little knowledge of the OpenID Connect protocol to setup authentication.

A special thanks goes to Justin Richer and Amanda Anganes for their help and support of the protocol.

Requirements

  1. PHP 5.4 or greater
  2. CURL extension
  3. JSON extension

Install

  1. Install library using composer
composer require jumbojett/openid-connect-php
  1. Include composer autoloader
require __DIR__ . '/vendor/autoload.php';

Example 1: Basic Client

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');

See openid spec for available user attributes

Example 2: Dynamic Registration

register(); $client_id = $oidc->getClientID(); $client_secret = $oidc->getClientSecret(); // Be sure to add logic to store the client id and client secret">
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

Example 3: Network and Security

setCertPath("/path/to/my.cert");">
// Configure a proxy
$oidc->setHttpProxy("http://my.proxy.com:80/");

// Configure a cert
$oidc->setCertPath("/path/to/my.cert");

Example 4: Request Client Credentials Token

use Jumbojett\OpenIDConnectClient;

$oidc = new OpenIDConnectClient('https://id.provider.com',
                                'ClientIDHere',
                                'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');

// this assumes success (to validate check if the access_token property is there and a valid JWT) :
$clientCredentialsToken = $oidc->requestClientCredentialsToken()->access_token;

Example 5: Request Resource Owners Token (with client auth)

use Jumbojett\OpenIDConnectClient;

$oidc = new OpenIDConnectClient('https://id.provider.com',
                                'ClientIDHere',
                                'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');

//Add username and password
$oidc->addAuthParam(array('username'=>''));
$oidc->addAuthParam(array('password'=>''));

//Perform the auth and return the token (to validate check if the access_token property is there and a valid JWT) :
$token = $oidc->requestResourceOwnerToken(TRUE)->access_token;

Example 6: Basic client for implicit flow e.g. with Azure AD B2C (see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth)

use Jumbojett\OpenIDConnectClient;

$oidc = new OpenIDConnectClient('https://id.provider.com',
                                'ClientIDHere',
                                'ClientSecretHere');
$oidc->setResponseTypes(array('id_token'));
$oidc->addScope(array('openid'));
$oidc->setAllowImplicitFlow(true);
$oidc->addAuthParam(array('response_mode' => 'form_post'));
$oidc->setCertPath('/path/to/my.cert');
$oidc->authenticate();
$sub = $oidc->getVerifiedClaims('sub');

Example 7: Introspection of an access token (see https://tools.ietf.org/html/rfc7662)

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
}

Example 8: PKCE Client

use Jumbojett\OpenIDConnectClient;

$oidc = new OpenIDConnectClient('https://id.provider.com',
                                'ClientIDHere',
                                null);
$oidc->setCodeChallengeMethod('S256');
$oidc->authenticate();
$name = $oidc->requestUserInfo('given_name');

Development Environments

In some cases you may need to disable SSL security on on your development systems. Note: This is not recommended on production systems.

$oidc->setVerifyHost(false);
$oidc->setVerifyPeer(false);

Also, your local system might not support HTTPS, so you might disable uprading to it:

$oidc->setHttpUpgradeInsecureRequests(false);

Todo

  • Dynamic registration does not support registration auth tokens and endpoints

Contributing

  • All pull requests, once merged, should be added to the CHANGELOG.md file.
Comments
  • Getting  redirect_uri_mismatch on OpenAM

    Getting redirect_uri_mismatch on OpenAM

    I am getting this page:

    Error: redirect_uri_mismatch

    Description: The redirection URI provided does not match a pre-registered value.

    I have added the client secret &c to the client. Also when I add the redirect URL as:

    http://m.y.i.p.:port/folder/client_example.php on OpenAM OpenID Connect Server, I get a redirect loop.

    opened by rghose 22
  • Problems using Google as the provider

    Problems using Google as the provider

    I'm trying to use this library to log into a Mediawiki instance using its OpenID Connect sign-in plugin and am using Google as the provider. I use the Google Developer's Console to obtain the Client ID and Client Secret from the project. Unfortunately, I run into a few issues that require manual changes to the code:

    1. Nonce values are not accepted by Google's servers, so I need to comment out the nonce code or else the Google servers will return an error.
    2. The log in sometimes will work, while other times, there is an issue with the RSA key verification and the login will fail. I'm not sure if it's a problem with Google or if it's a problem with the Mediawiki's server's security. I don't know much about how encryption works, so I'm very lost. It might be caused by the disabled noncing I mentioned above. I'm also considering if it's a problem with proxies, but again, I don't know for sure anything. If you know anything that can help with this, or need certain information to help, let me know.
    opened by mhauslerArcweb 14
  • Some commit broke IdentityServer3 compatibility

    Some commit broke IdentityServer3 compatibility

    opened by svrooij 13
  • Is there a list of providers that work with OpenID-Connect-PHP?  Does it work with GitHub

    Is there a list of providers that work with OpenID-Connect-PHP? Does it work with GitHub

    I have been able to use this with Google and SalesForce

    • ... = new OpenIDConnectClient("accounts.google.com", '28...", "9328");
    • ... = new OpenIDConnectClient("https://login.salesforce.com", '3MV...", "xyz");

    Has any one been able to use this with GitHub and others? if so can you share how you connected.

    opened by zmon 11
  • undefined index $_SESSION['openid_connect_state']

    undefined index $_SESSION['openid_connect_state']

    Hi I tried to use basic authentication from example but got error on line 1090

    Undefined index: openid_connect_state
    

    my code is

      $oidc = new OpenIDConnectClient($providerUrl, $clientId, $clientSecret);
    
      $oidc->authenticate();
      $oidc->addScope('email');
    
      $clientCredentialsToken = $oidc->requestClientCredentialsToken();
    

    Thanks for any help

    opened by LubomirIgonda1 10
  • Security fix: Use random_bytes() instead of uniqid()

    Security fix: Use random_bytes() instead of uniqid()

    This security fix will break compatibility with PHP versions prior to 7.0. But in my opinion, it doesn't matter since these are End-of-Life since more than a year. Anyway, including random_compat may be a solution.

    RFC 6749 recommends CSRF protection via state parameter. Therefore, its value needs to be cryptographically secure (uniqid does not provide that). The OIDC-Spec states the same for nonce:

    The nonce parameter value needs to include per-session state and be unguessable to attackers. One method to achieve this for Web Server Clients is to store a cryptographically random value as an HttpOnly session cookie and use a cryptographic hash of the value as the nonce parameter.

    List of common tasks a pull request require complete

    • [x] Changelog entry is added or the pull request don't alter library's functionality
    opened by JuliusPC 9
  • Refactor library to function as standalone plugin

    Refactor library to function as standalone plugin

    Currently, this library can only be used by including the single source file in the application, directly loading global function which are never required in global scope.

    I think this library can benefit from some decent object oriented design, so that it can easily be reused by other libraries such as Symfony library.

    Currently, I've adapted this library to fit directly in my library, but are you interested to have it backported here?

    opened by bobvandevijver 8
  • Method requestResourceOwnerToken doesn't work without the header

    Method requestResourceOwnerToken doesn't work without the header

    Hi! Your library suits well in my project. Thanks! But when I use the method requestResourceOwnerToken, the request comes with an error. As it turned out, I need to add a header "Authorization: Basic" in the method. As in next method requestTokens. Then everything works. When you tested this method, did you have an error? It may be worth adding the possibility that the person who uses this library can add their own headers outside this method?

    opened by BigTonni 8
  •  provider authorization_endpoint has not been set.

    provider authorization_endpoint has not been set.

    Having some trouble, and not sure what's wrong.

    I've created a new OpenIDConnectClient by passing in the authorize url

    Then I get an error stating "the provider authorization_endpoint has not been set.

    How do I set that?

    I tried addauthparam, but that didn't work. Code snippet below.

    $providerurl = 'https://login.microsoftonline.com/xxxxx/oauth2/authorize';
    
    
    $clientID = 'abc123';  #azure Object ID
    $secret = 'secret';    #key in Azure settings
    
     $oidc = new OpenIDConnectClient($providerurl,
                                   $clientID,
                                 $secret);
    
    $oidc->addauthParam("authorization_endpoint", $providerurl);
    $oidc->authenticate();
    
    opened by jackfruh 8
  • Compatibility with GPLv2 Software

    Compatibility with GPLv2 Software

    Hello Michael,

    I am setting up authentication using your OpenID-Connect-PHP library in the fossology solution. However, I am blocked since Fossology is GPLv2, which is not compatible with ApacheV2.

    Would you possibly consider adding (for example) a BSD license so that it could be used along GPLv2 products ?

    This would be of great help, thanks,

    Nicolas

    opened by NicolasToussaint 7
  • Error in instructions?

    Error in instructions?

    Hi, the instructions say to require '/vendor/autoload.php';

    This assumes your project is on the root of a drive and returns an error if not: Fatal error: require(): Failed opening required '/vendor/autoload.php'

    opened by jackfruh 7
  • Add an extra check on $_REQUEST['state'] (issue #353)

    Add an extra check on $_REQUEST['state'] (issue #353)

    This will prevent php warning for php 8 project while trying to authenticate client.

    List of common tasks a pull request require complete

    • [ ] Fix php 8 warning on client authenticate
    opened by kastoras 0
  • Authenticate Problem on php 8

    Authenticate Problem on php 8

    If you use this library on a php 8 project with php warnings enabled you experience this problem.

    In OpenIDConnectClient class, in authenticate method there will be a warning in line 341 $_REQUEST['state'] that the state in not defined. And after this error you get this error Warning: Cannot modify header information - headers already sent by... and then it fails.

    I will provide a pull request, with an extra check if $_REQUEST['state'] exists.

    opened by kastoras 1
  • Problems using this package in a system with Azure AD

    Problems using this package in a system with Azure AD

    Hello, thanks for this lib.

    I'm a web dev without many experience on SSO and OIDC. I don't get how to work with OIDC and AzureAD.

    I need to build a complete "workflow" for users using a test app in AzureAD and my PHP system. There is: login, logout, get email or userid (sub).

    I build this script (ommit values specific of my app): https://gist.github.com/tomasdelvechio/5fa4d25cb7399eba21e33370f790a2d1#file-testing-php

    The above script redirect to AzureAD, let me login in success and return an id_token, state and session_state. But from this, I can't get the sub value, email, etc...

    From the AzureAD app I check the options redirect uri and ID tokens (used for implicit and hybrid flows).

    Questions:

    • I have to call authenticate() method in each request to my app? or is it enough with just create Oidc object?
    • Some software (open source) implement full the AzureAD API in php using this lib, to learn from there how to use the package for my app?
    • Some reference code or other material relevant? I read RFCs, OIDC doc online, this repo Wiki, issues, PRs, etc...
    opened by tomasdelvechio 0
  • fix: correct aud check in verifyLogoutTokenClaims

    fix: correct aud check in verifyLogoutTokenClaims

    previously, when aud was correct, the in_array clause was evaluated but failed with an error (aud is not array), so the verifyLogoutTokenClaims function returned false for a valid token

    List of common tasks a pull request require complete

    • [x] Changelog entry is added or the pull request don't alter library's functionality
    opened by melanger 2
  •  Enabled client_secret_basic authentication on requestClientCredentialsToken()

    Enabled client_secret_basic authentication on requestClientCredentialsToken()

    Fixes issue #347

    List of common tasks a pull request require complete

    • [x] Changelog entry is added or the pull request don't alter library's functionality
    opened by Magentron 0
Releases(v0.9.10)
  • v0.9.10(Sep 30, 2022)

  • v0.9.9(Sep 28, 2022)

    Added

    • Added support for back-channel logout. #302
    • Added support for private_key_jwt Client Authentication method #322

    Fixed

    • Harden self-signed JWK header usage. #323
    Source code(tar.gz)
    Source code(zip)
  • v0.9.8(Aug 5, 2022)

  • v0.9.7(Jul 13, 2022)

    Added

    • Support for Self-Contained JWTs. #308
    • Support for RFC8693 Token Exchange Request. #275

    Fixed

    • PHP 5.4 compatibility. #304
    • Use session_status(). #306
    Source code(tar.gz)
    Source code(zip)
  • v0.9.6(May 8, 2022)

    Added

    • Support for phpseclib/phpseclib version 3. #260
    • Support client_secret on token endpoint with PKCE. #293
    • Added new parameter to requestTokens() to pass custom HTTP headers #297

    Changed

    • Allow serializing OpenIDConnectClient using serialize() #295
    Source code(tar.gz)
    Source code(zip)
  • v0.9.5(Nov 24, 2021)

    Changed

    • signOut() Method parameter $accessToken -> $idToken to prevent confusion about access and id tokens usage. #127
    • Fixed issue where missing nonce within the claims was causing an exception. #280
    Source code(tar.gz)
    Source code(zip)
  • v0.9.4(Nov 21, 2021)

  • v0.9.3(Nov 20, 2021)

    Added

    • getRedirectURL() will not log a warning for PHP 7.1+ #179
    • it is now possible to disable upgrading from HTTP to HTTPS for development purposes by calling setHttpUpgradeInsecureRequests(false) #241
    • bugfix in getSessionKey when _SESSION key does not exist #251
    • Added scope parameter to refresh token request #225
    • bugfix in verifyJWTclaims when $accessToken is empty and $claims->at_hash is not #276
    • bugfix with the empty function in PHP 5.4 #267
    Source code(tar.gz)
    Source code(zip)
  • v0.9.2(Nov 16, 2020)

  • v0.9.1(Aug 27, 2020)

    Added

    • Add support for MS Azure Active Directory B2C user flows

    Changed

    • Fix at_hash verification #200
    • Getters for public parameters #204
    • Removed client ID query parameter when making a token request using Basic Auth

    Removed

    • Removed explicit content-length header - caused issues with proxy servers
    Source code(tar.gz)
    Source code(zip)
  • v0.9.0(Mar 9, 2020)

    Added

    • php 7.4 deprecates array_key_exists on objects, use property_exists in getVerifiedClaims and requestUserInfo
    • Adding a header to indicate JSON as the return type for userinfo endpoint #151
    • ~Updated OpenIDConnectClient to conditionally verify nonce #146~
    • Add possibility to change enc_type parameter for http_build_query #155
    • Adding OAuth 2.0 Token Introspection #156
    • Add optional parameters clientId/clientSecret for introspection #157 & #158
    • Adding OAuth 2.0 Token Revocation #160
    • Adding issuer validator #145
    • Adding signing algorithm PS256 #180
    • Check http status of request user info #186
    • URL encode clientId and clientSecret when using basic authentication, according to https://tools.ietf.org/html/rfc6749#section-2.3.1 #192
    • Adjust PHPDoc to state that null is also allowed #193

    Changed

    • Bugfix/code cleanup #152
      • Cleanup PHPDoc #46e5b59
      • Replace unnecessary double quotes with single quotes #2a76b57
      • Use original function names instead of aliases #1f37892
      • Remove unnecessary default values #5ab801e
      • Explicit declare field $redirectURL #9187c0b
      • Remove unused code #1e65384
      • Fix indent #e9cdf56
      • Cleanup conditional code flow for better readability #107f3fb
    • Added strict type comparisons #167
    • Bugfix: required openid scope was omitted when additional scopes were registered using addScope method. This resulted in failing OpenID process.
    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Jan 2, 2019)

    Added

    • Fix verifyJWTsignature(): verify JWT to prevent php errors and warnings on invalid token

    Changed

    • Decouple session manipulation, it's allow use of other session libraries #134
    • Broaden version requirements of the phpseclib/phpseclib package. #144
    Source code(tar.gz)
    Source code(zip)
  • 0.7.0(Oct 15, 2018)

    [0.7.0]

    Added

    • Add "license" field to composer.json #138
    • Ensure key_alg is set when getting key #139
    • Add option to send additional registration parameters like post_logout_redirect_uris. #140

    Changed

    • disabled autoload for Crypt_RSA + makre refreshToken() method tolerant for errors #137
    Source code(tar.gz)
    Source code(zip)
  • 0.6.0(Jul 17, 2018)

    Added

    • Added five minutes leeway due to clock skew between openidconnect server and client.
    • Fix save access_token from request in implicit flow authentication #129
    • verifyJWTsignature() method private -> public #126
    • Support for providers where provider/login URL is not the same as the issuer URL. #125
    • Support for providers that has a different login URL from the issuer URL, for instance Azure Active Directory. Here, the provider URL is on the format: https://login.windows.net/(tenant-id), while the issuer claim actually is on the format: https://sts.windows.net/(tenant-id).

    Changed

    • refreshToken method update #124
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Apr 9, 2018)

  • 0.4.1(Feb 16, 2018)

  • 0.4.0(Feb 15, 2018)

    Added

    • Timeout is configurable via setTimeout method. This addresses issue #94.
    • Add the ability to authenticate using the Resource Owner flow (with or without the Client ID and ClientSecret). This addresses issue #98
    • Add support for HS256, HS512 and HS384 signatures
    • Removed unused calls to $this->getProviderConfigValue("token_endpoint_…
    Source code(tar.gz)
    Source code(zip)
PHP implementation of openid connect-core

OIDC Discovery PHP implementation of https://openid.net/specs/openid-connect-core-1_0.html Install Via Composer $ composer require digitalcz/openid-co

DigitalCz 3 Dec 14, 2022
:atom: Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP :shipit:

SocialConnect Auth Getting Started :: Documentation :: Demo Open source social sign on PHP. Connect your application(s) with social network(s). Code e

SocialConnect 518 Dec 28, 2022
:atom: Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP :shipit:

SocialConnect Auth Getting Started :: Documentation :: Demo Open source social sign on PHP. Connect your application(s) with social network(s). Code e

SocialConnect 458 Apr 1, 2021
Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP

Open source social sign on PHP. Connect your application(s) with social network(s).

SocialConnect 517 Dec 11, 2022
Laravel with NTPC OpenID skeleton

這是啥? 本專案已整合了新北市 OpenID 登入,實作了基本身分驗證系統。 本機帳號登入 新北市 OpenID 登入,初次登入時會建立本機帳號,密碼隨機產生 系統需求 PHP 建議使用 8.0.11 以上 使用方式 以下 FOLDER_NAME 自行替換成想要的資料夾名稱 執行 git clone

null 1 Oct 27, 2021
EAuth extension allows to authenticate users by the OpenID, OAuth 1.0 and OAuth 2.0 providers

EAuth extension allows to authenticate users with accounts on other websites. Supported protocols: OpenID, OAuth 1.0 and OAuth 2.0.

Maxim Zemskov 330 Jun 3, 2022
Open Id Connect Api

flux-open-id-connect-api Open Id Connect Api Installation Native Download RUN (mkdir -p /%path%/libs/flux-open-id-connect-api && cd /%path%/libs/flux-

null 1 Dec 12, 2022
The Salla OAuth Client library is designed to provide client applications with secure delegated access to Salla Merchant stores.

Salla Provider for OAuth 2.0 Client This package provides Salla OAuth 2.0 support for the PHP League's OAuth 2.0 Client. To use this package, it will

Salla 14 Nov 27, 2022
HTTP Basic Auth Guard for Lumen 5.x

HTTP Basic Auth Guard HTTP Basic Auth Guard is a Lumen Package that lets you use basic as your driver for the authentication guard in your application

Christopher Lass 40 Nov 11, 2022
This is a basic Oauth2 authorization/authentication server implemented using Mezzio.

Mezzio-OAuth2-Authorization-Authentication-Server This is a basic OAuth2 authorization/authentication server implemented using Mezzio. I have found so

null 1 Nov 15, 2022
Configurable Basic Auth based on Pimcore Documents

CORS Property Basic Auth This bundles allows to add basic auth based on Properties on Pimcore Documents. Simply use these properties password_enabled

CORS GmbH 1 Nov 12, 2021
PSR-7 and PSR-15 HTTP Basic Authentication Middleware

PSR-7 and PSR-15 Basic Auth Middleware This middleware implements HTTP Basic Authentication. It was originally developed for Slim but can be used with

Mika Tuupola 430 Dec 30, 2022
Basic Authentication handler for the JSON API, used for development and debugging purposes

Basic Authentication handler This plugin adds Basic Authentication to a WordPress site. Note that this plugin requires sending your username and passw

WordPress REST API Team 667 Dec 31, 2022
Stateless HTTP basic auth for Laravel without the need for a database.

Laravel Very Basic Auth Documentation available in: ???? English ???? 日本語 This package allows you to add a HTTP Basic Auth filter on your routes, with

Marcus Olsson 141 Dec 31, 2022
PHP 5.3+ oAuth 1/2 Client Library

PHPoAuthLib NOTE: I'm looking for someone who could help to maintain this package alongside me, just because I don't have a ton of time to devote to i

David Desberg 1.1k Dec 27, 2022
PHP Client and Router Library for Autobahn and WAMP (Web Application Messaging Protocol) for Real-Time Application Messaging

Thruway is an open source client and router implementation of WAMP (Web Application Messaging Protocol), for PHP. Thruway uses an event-driven, non-blocking I/O model (reactphp), perfect for modern real-time applications.

Voryx 662 Jan 3, 2023
GoSign OneSign PHP API client

OneSign PHP API Client Reikalavimai PHP 7.4+ arba 8.0+ Patariam Nginx php-fpm Funkcijos PDF dokumentų pasirašymas; laiko žymų uždėjimas ant PDF dokume

Registrų centras 5 Nov 28, 2021
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 256 Nov 16, 2022
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 261 Jan 17, 2022