How to get token Machine to Machine with php Auth0 sdk and not curl?

Hello everyone,

I need help, please. I’m using a free trial to test Auth0, and I want to test Machine-to-Machine authentication to obtain a token.

The following cURL request from the Auth0 dashboard works correctly, and I receive the token:

 $curl = curl_init();

            curl_setopt_array($curl, array(
            CURLOPT_URL => "https://dev-2qs4dcflvo4nycaq.us.auth0.com/oauth/token",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\"client_id\":\"client_id\",\"client_secret\":\"client_secret\",\"audience\":\"http://api-gateway.localhost/\",\"grant_type\":\"client_credentials\"}",
            CURLOPT_HTTPHEADER => array(
                "content-type: application/json"
            ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
            echo "cURL Error #:" . $err;
            } else {
             echo $response;
            }

However, I want to use the Auth0 PHP SDK for this, but it seems impossible because I keep getting errors. It’s complicated, and I receive an Unauthorized 401 error even though I use the same credentials.

Here is my Auth0 SDK implementation:

  $auth0 = new Auth0([
                'domain' => 'dev-2qs4dcflvo4nycaq.us.auth0.com',
                'clientId' => 'client_id',
                'clientSecret' => 'client_secret,
                'grant_type' => 'client_credentials',
                // 'strategy' => SdkConfiguration::STRATEGY_API,
                'audience' => ['http://api-gateway.localhost/'],
     'cookieSecret' => 'test'
            ]);
            dd($auth0->authentication()->clientCredentials([
                'audience' => 'http://api-gateway.localhost/'
            ]));

I get a 401 Unauthorized error, and there is no useful information in the Auth0 monitoring dashboard.

I’ve tested different functions…

Do you have any idea what the problem could be?

Thanks!

Hi @kevin.schmitt.upjv,

Your code looks correct by calling the clientCredentials() method to get an access token for your M2M application.

If you are getting 401 Unauthorized error, I suggest ensuring all the values you provided are correct, such as the clientID and clientSecret.

Here are some references on getting a token for your M2M app using the Auth0 PHP SDK:

Thanks,
Rueben