Coder Social home page Coder Social logo

auth0-php's Introduction

auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

Package Build Status Coverage License

๐Ÿ“š Documentation - ๐Ÿš€ Getting Started - ๐Ÿ’ป API Reference ๐Ÿ’ฌ Feedback

Documentation

We also have tailored SDKs for Laravel, Symfony, and WordPress. If you are using one of these frameworks, use the tailored SDK for the best integration experience.

Getting Started

Requirements

Please review our support policy for details on our PHP version support.

Installation

Ensure you have the necessary dependencies installed, then add the SDK to your application using Composer:

composer require auth0/auth0-php --no-dev

Configure Auth0

Create a Regular Web Application in the Auth0 Dashboard. Verify that the "Token Endpoint Authentication Method" is set to POST.

Next, configure the callback and logout URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: The URL of your application where Auth0 will redirect to during authentication, e.g., http://localhost:3000/callback.
  • Allowed Logout URLs: The URL of your application where Auth0 will redirect to after user logout, e.g., http://localhost:3000/login.

Note the Domain, Client ID, and Client Secret. These values will be used later.

Add login to your application

Create a SdkConfiguration instance configured with your Auth0 domain and Auth0 application client ID and secret. Generate a sufficiently long, random string for your cookieSecret using openssl rand -hex 32. Create a new Auth0 instance and pass your configuration to it.

use Auth0\SDK\Auth0;
use Auth0\SDK\Configuration\SdkConfiguration;

$configuration = new SdkConfiguration(
    domain: 'Your Auth0 domain',
    clientId: 'Your Auth0 application client ID',
    clientSecret: 'Your Auth0 application client secret',
    cookieSecret: 'Your generated string',
);

$auth0 = new Auth0($configuration);

Use the getCredentials() method to check if a user is authenticated.

// getCredentials() returns null if the user is not authenticated.
$session = $auth0->getCredentials();

if (null === $session || $session->accessTokenExpired) {
    // Redirect to Auth0 to authenticate the user.
    header('Location: ' . $auth0->login());
    exit;
}

Complete the authentication flow and obtain the tokens by calling exchange():

if (null !== $auth0->getExchangeParameters()) {
    $auth0->exchange();
}

Finally, you can use getCredentials()?->user to retrieve information about our authenticated user:

print_r($auth0->getCredentials()?->user);

That's it! You have successfully authenticated your first user with Auth0! From here, you may want to try following along with one of our quickstarts or browse through our examples for additional insight and guidance.

If you have questions, the Auth0 Community is a fantastic resource to ask questions and get help.

API Reference

Support Policy

Our support lifecycle mirrors the PHP release support schedule.

SDK Version PHP Version Support Ends
8 8.3 Nov 2026
8.2 Nov 2025
8.1 Nov 2024

We drop support for PHP versions when they reach end-of-life and cease receiving security fixes from the PHP Foundation. Please ensure your environment remains up to date so you can continue receiving updates for PHP and this SDK.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy-to-implement, adaptable authentication and authorization platform.
To learn more, check out "Why Auth0?"

This project is licensed under the MIT license. See the LICENSE file for more info.

auth0-php's People

Contributors

abbaspour avatar annyv2 avatar b-galati avatar cocojoe avatar crecket avatar damieng avatar darkyen avatar deboorn avatar dependabot[bot] avatar evansims avatar frederikprijck avatar glena avatar hrajchert avatar jimmyjames avatar joshcanhelp avatar jrfnl avatar jspetrak avatar kler avatar lbalmaceda avatar mgonto avatar ntotten avatar nyholm avatar pinodex avatar ramonschriks avatar ring avatar robinvdvleuten avatar sepiariver avatar siacomuzzi avatar udf2457 avatar vmartynets avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-php's Issues

JWTVerifier exp verification

Hi,

From a quick look at the code it seems that the verifyanddecode process doesn't check the exp of the JWT ?

Exception: Cannot handle token prior to [timestamp]

As I mentioned in this issue (over in PHP-JWT), I'm getting this exception triggered a lot when calling $auth0->getUser(). It first happened on my development machine and now on my web host:

Cannot handle token prior to 2016-01-15T14:44:28+1100

It appears to occur when the server's clock is a few seconds behind Auth0's. I resynced my local dev machine's clock and the message went away. I can't do that on a shared web hosting server though. :-(

My thoughts are that the time check should not be so strict that it requires an up-to-the-second time-synchronization.

Simon.

More descriptive readme file with instructions about how to download dependencies using composeri

After downloading this seed project, the readme file doesn't specify the path to get all the dependencies needed for the project in order to work properly. The existing text in the readme file in the 'Running this example' section is:

Running the example

In order to run the example you need to have composer and php installed.

You also need to set the ClientSecret, ClientId, Domain and Callback URL for your Auth0 app as environment variables with the following names respectively: AUTH0_CLIENT_SECRET, AUTH0_CLIENT_ID, AUTH0_DOMAIN and AUTH0_CALLBACK_URL.

For that, if you just create a file named .env in the directory and set the values like the following, the app will just work:

# .env file
AUTH0_CLIENT_SECRET=myCoolSecret
AUTH0_CLIENT_ID=myCoolClientId
AUTH0_DOMAIN=yourDomain.auth0.com
AUTH0_CALLBACK_URL=http://your.url/

Once you've set those 4 environment variables, just run the following to get the app started:

composer install
php -S localhost:3000

So I suggest to add the information existing in the tutorial which specify after the instalation of composer, to run the following command:

To install dependencies, run the following

composer require auth0/auth0-php:"~3.0"

authParams... how do I retrieve the results?

After a successful log, how to I reveal the values of authParams? I can see the returned url contains the state parameter:

https://mydomain.net/public/login/?code=MKeyK8NNe5dijXW3&state=zRx4w7thku0XAqlN

However, state is encoded... I'm trying to make a callback url to the original location where the user came from.

function signin() {

    lock.show({
        callbackURL: AUTH0_CALLBACK_URL
      , icon: '/app/images/auth0-badge.png'
      , socialBigButtons: true
      , disableResetAction: true

      , authParams: {
        orig_callback_url: getParameterByName('callback_url')
      }

    });

}

Test

this is for testing the channel integration

Method to retrieve refresh token

Hi,

Is there a way to fetch the refresh token from the request?

I can see it if I:

        private function exchangeCode(): ...
           var_dump($auth0_response);
           die();

I'd like to store this on the user (backend only) so I can renew their token if their session is about to expire.

Create password change ticket fails

src/API/Management/Tickets.php

Method createPasswordChangeTicket, the apiClient post header is missing 'application/json', resulting in a invalid body error.

Also, the method should have a default value of null for $new_password, and should only get added to $body if not null, as the new password field is optional in the API.

basic-webapp project relative path

Related to lines 41 and 42 at basic-webapp project. If i host this project like http://localhost/basic-webapp this files would be included from http://localhost/public/, not from http://localhost/basic-webapp/public/

Error at Auth0JWT::encode when using custom payload

The Auth0\SDK\Auth0JWT does not add custom payload to the generated JWT.

The following lines atAuth0JWT::encode:

<?php
// Auth0\SDK\Auth0JWT
if ($custom_payload) {
    $custom_payload = array_merge($custom_payload, $payload);
}

should be:

<?php
// Auth0\SDK\Auth0JWT
if ($custom_payload) {
    $payload = array_merge($custom_payload, $payload);
}

Is it correct or am I missing something?

Typo on README

The basic webapp example says this AUTH0_CLIENT_SECRET and AUTH0_CLIENT_ID, AUTH0_DOMAIN, AUTH0_CALLBACK_URL.

Error in composer install

Hello,

When I'm trying to install the package I receive this error:

Problem 1
- auth0/auth0-php 1.0.6 requires firebase/php-jwt dev-master -> no matching package found.
- auth0/auth0-php 1.0.5 requires firebase/php-jwt dev-master -> no matching package found.
- auth0/auth0-php 1.0.4 requires firebase/php-jwt dev-master -> no matching package found.
- auth0/auth0-php 1.0.3 requires firebase/php-jwt dev-master -> no matching package found.
- auth0/auth0-php 1.0.2 requires firebase/php-jwt dev-master -> no matching package found.
- auth0/auth0-php 1.0.1 requires firebase/php-jwt dev-master -> no matching package found.
- auth0/auth0-php 1.0.0 requires firebase/php-jwt dev-master -> no matching package found.
- Installation request for auth0/auth0-php ~1.0 -> satisfiable by auth0/auth0-php[1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.0.6].

This seems related with googlearchive/firebase-token-generator-php#15

I'm following the instructions from the quickstart.

Unexpected token

I'm testing basic-webapp am seeing the following console errors:

SyntaxError: Unexpected token '<'            10122*****klab.appsgoogleusercontent.com.js:1

it's just not working... any ideas?

Undefined user_metadata error thrown

When I try to get the user_metadata it will throw a error since the user's meta data is not set by default. #107

$Auth0 = new Auth0\SDK\Auth0(
// options
);
$app['Auth0']->getUserMetadata();

This causes:

ContextErrorException in Oauth2Client.php line 333:
Notice: Undefined index: user_metadata

This can easily be solved by returning a empty array or NULL if no metadata is set.

Missing updateAppMetadata() method?

I noticed the following methods in Auth0.php, but no method to update AppMetadata for the user.

updateUserMetadata($metadata)
getUserMetadata()
getAppMetadata()

Any reason for this? Is there a way to set app metadata in the version on composer?

JWTVerifier.php incorrect exception being thrown

JWTVerifier is throwing the exception "The client_secret is mandatory when accepting HS256 signed tokens".

This is despite the fact I am initialising it as below for RS256 only.

$validatorConfig=[];
$validatorConfig['guzzle_options']=['curl'=>[\CURLOPT_IPRESOLVE =>\CURL_IPRESOLVE_V4]];
$validatorConfig['suported_algs']=['RS256'];
$validatorConfig['valid_audiences']=['xxxxxxxxxxxxxxxxxxxxxxxxxx'];
$validatorConfig['authorized_iss']=['https://example.eu.auth0.com/'];
$validator=new \Auth0\SDK\JWTVerifier($validatorConfig);
$validator->verifyAndDecode($token);

Class 'JWT' not found

It appears the namespace of the JWT class from the firebase/php-jwt has changed and therefore the usage in the Auth0 SDK no longer works.

Linked Accounts

Hi there,

Understandably this might be more of an Auth0 issue rather than the PHP SDK issue, but I'm wondering how we can get the primary users JWT after login?

e.g.

  1. User registers using Facebook
  2. User signs out
  3. User comes back and registers with Google

How do we obtain the token of the Facebook account when the user logs in with a secondary account? We require this token so we can continue to make authenticated API calls to the users initial (primary) account.

PHP should be 5.4+, not 5.3+

In the composer file, it requires PHP 5.3+, I think that's misleading because it's not going to run under 5.3 due to at least one dependency, Guzzle.

User is null not false

I have found an issue using custom session storage. I am unable to successfully get a user from Auth0 because the exchangeCode() method is never being called.

I think I have narrowed this down to a combination of line 198 and line 276 in the Auth0.php file.

Line 198:

$this->user = $this->store->get("user");

When a key is returned from my session storage and there was nothing stored against that key, I get the value null. This is then assigned to $this->user.

On line 276 the following check is made:

if ($this->user === false) {
        $this->exchangeCode();
}

Seeing as the user variable is set to null and not false this method is never called and I get returned false for my user.

I have resolved this by changing the check to:

if (!$this->user) {
        $this->exchangeCode();
}

Which is allowing me to get the user.

Update to use v3.0 of firebase/php-jwt

Hello,

The current library is using an old version of the firebase/php-jwt library, which is now out of date. Can you update your software to use the current version (v3.0)?

Here is output from composer that shows the problem when I try to include the "firebase/php-jwt":"~3.0":

$ ./composer.phar update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for auth0/auth0-php ~2.0 -> satisfiable by auth0/auth0-php[2.0.0].
- auth0/auth0-php 2.0.0 requires firebase/php-jwt ~2.2 -> no matching package found.

Potential causes:

Read https://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

/tokeninfo API support

Does this SDK support making calls to /tokeninfo with a user's JWT token?

I can't find support for either of the User profile endpoints in this SDK

RS256 Signing - Code incomplete

Looks like someone was working on RS256 signing, and didn't get around to finish it. :P

  • A self method is called here, but the method does not exist. It appears to be deprecated, in favor it Auth0\SDK\Helpers\JWKFetcher@fetchKeys().
  • There's an added slash here

Guzzle 6

The application I'm working on is using several packages using guzzle 6, which means I cannot require this package.

Correct way to use the JWT Token generated in API v2 if we want expanded scope

Hi,
We're trying to build a small management admin dashboard for our Auth0 setup, and we want to give rights to our admins in this app to create new users and update existing user data.

We've generated the token in the API v2 section, but it's not clear on how to use this token with the Auth0 PHP SDK class.

Could you share some insight on the correct way to use this?

Thanks in advance.

Outdated Lock

Basic web app and some of the other examples in this repositories are using outdated versions of lock

Example is out of date

For newcomers, it would be helpful to see the updated example for auth0/lock. Documentation states Auth0Widget is now deprecated in place of Lock.

This example project is currently using the deprecated module.

generateUrl() in BaseAuth0 is creating bad URLs

When I make the following call for creating a User URL

$url = $this->generateUrl('api', '/users');

it returns https://company.auth0.com/apiusers

The problem seems to be the '/' removing part of this function

final protected function generateUrl($domain_key, $path = '/') 
{
    $base_domain = self::$URL_MAP[$domain_key];
    $base_domain = str_replace('{domain}', $this->domain, $base_domain);

    if ($path[0] === '/') {
        $path = substr($path, 1);
    }

    return $base_domain.$path;
}

There's two easy ways to fix this issue:

  1. Remove the if ($path[0] ==='/') {...etc lines from the function OR
  2. In $URL_MAP add a '/' character to the end of each url. So turn

public static $URL_MAP = array( 'api' => 'https://{domain}/api', 'authorize' => 'https://{domain}/authorize', 'token' => 'https://{domain}/oauth/token', 'user_info' => 'https://{domain}/userinfo', );

into

public static $URL_MAP = array( 'api' => 'https://{domain}/api/', 'authorize' => 'https://{domain}/authorize/', 'token' => 'https://{domain}/oauth/token/', 'user_info' => 'https://{domain}/userinfo/', );

Stable dependencies in composer.json instead of "dev-master"

Hi,

I've seen that in your dependencies list you have them defined as:

"require": {
    "php": ">=5.3.0",
    "guzzlehttp/guzzle": "~5.0",
    "ext-json": "*",
    "adoy/oauth2": "dev-master",
    "firebase/php-jwt" : "~2.2"
  },

The "adoy/oauth2" component has stable version 1.2.0: https://packagist.org/packages/adoy/oauth2

Is it there any reason to use the "dev-master" instead the stable version?

As you may know rely on development dependencies makes your software so fragile and it can break at any time after a "composer update" execution.

My suggestion is to update this component version to: "adoy/oauth2": "~1.2"

Regards,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.