judasprabin/auth-manager

为Lumen/Laravel提供的Auth0包装器

v10.0 2024-01-23 01:44 UTC

README

使用PHP 8.0版本管理Lumen和Laravel在微服务中的Auth0集成。

安装

通过composer

$ composer require carsguide/auth-manager

环境设置 .env文件

AUTH0_AUDIENCE=
AUTH0_OAUTH_URL=
AUTH0_DOMAIN=
AUTH0_JWT_CLIENTID=
AUTH0_JWT_CLIENTSECRET=
AUTH0_ALGORITHM=

注册服务提供者

Lumen

将以下代码片段添加到bootstrap/app.php文件中的服务提供者注册部分

$app->register(Carsguide\Auth\Providers\AuthManagerServiceProvider::class);

Laravel

将以下代码片段添加到config/app.php文件中的服务提供者注册部分

Carsguide\Auth\Providers\AuthManagerServiceProvider::class,

注册中间件

要使用令牌和范围验证,通过routeMiddleware()注册中间件

Lumen: bootstrap/app.php

$app->routeMiddleware([
    'auth' => Carsguide\Auth\Middlewares\Auth0Middleware::class,
]);

Laravel: app/Http/kernel.php

protected $routeMiddleware = [
    'auth' => \Carsguide\Auth\Middlewares\Auth0Middleware::class,
];

使用

生成JWT令牌

use Carsguide\Auth\AuthManager;
use GuzzleHttp\Client;

$auth = new AuthManager(new Client());
$auth = $auth->setAudience('foobar');
$auth->getToken();

使用AuthManager外观

use Carsguide\Auth\Facades\AuthManager;

AuthManager::setAudience('foobar')->getToken();

缓存JWT令牌

 AuthManager::setAudience('foobar')
    // By default, JWT will cache for 50 minutes
    // If you need to override the default length, 
    // pass minutes in cache(120) method.
    ->cache() // or ->cache($minutes = 120)
    ->getToken();

验证JWT令牌/范围访问

每个令牌都通过中间件进行验证。您必须在路由或控制器中调用中间件以验证访问。中间件需要定义范围,不能是全局的。

$this->middleware('auth:listings:read');

使用路由文件

$router->get('admin/profile', ['middleware' => 'auth:listings:read', function () {
    //
}]);