简体   繁体   English

是什么阻止了此 Laravel 8 API 中的 Auth0 授权?

[英]What prevents the Auth0 authorization in this Laravel 8 API?

I am working on a Laravel 8 API.我正在研究 Laravel 8 API。 I use Auth0 for user registration and login.我使用 Auth0 进行用户注册和登录。

I need the user's id returned by Auth0 to use in my own application.我需要 Auth0 返回的用户 ID 才能在我自己的应用程序中使用。

For this purpose I have the code:为此,我有代码:

In routes\api.php :routes\api.php

// Public routes
Route::get('/authorize', [AuthController::class, 'authorize']);

// Protected routes
Route::group(['middleware' => ['jwt']], function () {
  Route::get('/user-profile', [UserController::class, 'getUserId']);
  // More routes
});

In the AuthController :AuthController 中

namespace App\Http\Controllers;
use App\Http\Controllers\AuthController;
// More code

class AuthController extends Controller {
    protected $appDomain;
    protected $appClientId;
    protected $appClientSecret;
    protected $appAudience;
    
    public function authorize(){

        $this->appDomain = 'https://' . config('laravel-auth0.domain');
        $this->appClientId = config('laravel-auth0.client_id');
        $this->appClientSecret = config('laravel-auth0.client_secret');
        $this->appAudience = config('laravel-auth0.api_identifier');

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "$this->appDomain/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\":\"$this->appClientId\",\"client_secret\":\"$this->appClientSecret\",\"audience\":\"$this->appAudience\",\"grant_type\":\"client_credentials\"}",
            CURLOPT_HTTPHEADER => array(
                "content-type: application/json"
            ),
        ));

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

        curl_close($curl);

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

In the UserController :用户控制器中:

class UserController extends AuthController {
    // More code
    public function getUserId(){

        // Do authorization
        parent::authorize();

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "$this->appDomain/userinfo",
            CURLOPT_HTTPHEADER => array(
                "content-type: application/json"
            ),
        ));

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

        curl_close($curl);

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

    // More code
}

The problem问题

When I access the /user-profile route, Potman throws an Unauthorized response.当我访问/user-profile路由时,Potman 会抛出Unauthorized的响应。

This happend despite the fact that the /authorize route does return the token:尽管/authorize路由确实返回了令牌,但还是发生了这种情况:

{"access_token":"somerandom.longtoken","scope":"read:users update:users delete:users","expires_in":86400,"token_type":"Bearer"}

Question问题

Where is my mistake?我的错误在哪里?

UPDATE更新

Folowing the answer from @IProSoft, in the UserController I have:根据@IProSoft 的回答,在UserController中我有:

public function getUserId(){

    $access_token = parent::authorization()->access_token;

    $client = new \GuzzleHttp\Client;
        try {
                $client = new \GuzzleHttp\Client(['headers' => [
                        'authorization' => 'Bearer' . $access_token,
                        'content-type' => 'application/json'
                ]]);
                
                $response = $client->request('GET', $this->appDomain . '/userinfo');

                $response = json_decode($response->getBody());
        }
        catch (\GuzzleHttp\Exception\ClientException $e) {
                $response = $e->getResponse();
        }

        return  $response;
}

I get this error in Postman:我在 Postman 中收到此错误:

Error: Class 'Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory' not found in \vendor\laravel\framework\src\Illuminate\Routing\Router.php 
What causes this error?是什么导致了这个错误?

This code is only for show You the way, not checked etc.此代码仅用于向您展示方式,未检查等。

First thing install and learn Guzzle首先安装和学习 Guzzle

composer require guzzlehttp/guzzle:^7.0

In authorize method You can change everything to:在授权方法中,您可以将所有内容更改为:

$client = new GuzzleHttp\Client;
try {
    $client = new \GuzzleHttp\Client();
    $response = $client->request('POST', $this->appDomain . '/oauth/token', [
        'form_params' => [
            {
                "client_id":        $this->appClientId,
                "client_secret":    $this->appClientSecret,
                "audience":         $this->appAudience,
                "grant_type":       "client_credentials"
            }
        ]
    ]);

    $response = json_decode($response->getBody());
}
catch (GuzzleHttp\Exception\ClientException $e) {
    $response = $e->getResponse();
}

return $response;

Second: If you want get user id, You must pass Barer token in request第二:如果要获取用户ID,则必须在请求中传递Barer令牌

$client = new GuzzleHttp\Client;
try {
    $client = new \GuzzleHttp\Client('headers' => [
        'authorization' => 'Bearer ACCESS_TOKEN'
        'content-type' => 'application/json'
    ]]);
    $response = $client->request('GET', $this->appDomain . '/userinfo');

    $response = json_decode($response->getBody());
}
catch (GuzzleHttp\Exception\ClientException $e) {
    $response = $e->getResponse();
}

You don't have to reinvent the wheel:-) There is a ready library that you could use and all info can be found here: https://auth0.com/docs/quickstart/webapp/laravel/01-login您不必重新发明轮子:-) 有一个现成的库可供您使用,所有信息都可以在这里找到: https://auth0.com/docs/quickstart/webapp/laravel/01-login

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM