supaapps / supaapps-guard
一个 JWT 认证驱动,专为与 supaapps-auth-server 一起使用而设计
v0.6.0
2024-09-08 12:30 UTC
Requires
- php: ^8.1 || ^8.3
- firebase/php-jwt: ^6.10
- illuminate/auth: ^10.0 || ^11.0
- illuminate/contracts: ^10.0 || ^11.0
- illuminate/database: ^10.0 || ^11.0
- illuminate/http: ^10.0 || ^11.0
- illuminate/support: ^10.0 || ^11.0
Requires (Dev)
- nunomaduro/collision: ^7.8
- orchestra/testbench: ^8.21
- squizlabs/php_codesniffer: ^3.8
- dev-main
- v0.6.0
- v0.5.0
- v0.4.0
- v0.3.0
- v0.2.0
- v0.1.7
- v0.1.6
- v0.1.5
- v0.1.4
- v0.1.3
- v0.1.2
- v0.1.1
- v0.1.0
- dev-bugfix/SGRD-7_Remove_incrementing_from_users_table_to_allow_creation_of_logged_in_user_locally
- dev-feature/SGRD-4_add-usage-test-case-functions-to-generate-jwt-trait
- dev-feature/SGRD-6_check-scope-has-role-and-return-it
- dev-feature/SGRD-5_align_with_laravel_contracts_for_auth_guard
- dev-feature/SGRD-3_Check_revoked_token_ids_cache_them_for_15_seconds
- dev-feature/SGRD-2_ability_to_test_jwt_auth_guard
This package is auto-updated.
Last update: 2024-09-08 12:32:13 UTC
README
安装
composer require supaapps/supaapps-guard
环境变量
将环境变量添加到您的 .env
SUPAAPPS_GUARD_AUTH_SERVER_URL=http://example.com SUPAAPPS_GUARD_AUTH_REALM_NAME=myapp
添加新的自定义守卫
在 config/auth.php 中添加新的守卫
'guards' => [ 'jwt' => [ 'driver' => 'supaapps-guard', 'provider' => 'users', ], ],
此外,将默认守卫设置为 jwt
'defaults' => [ 'guard' => 'jwt', ...
使用示例
在 routes/api.php 中,添加以下行
Route::middleware('auth:jwt')->get('/user', function (Request $request) { return [ $request->user(), auth()->firstName(), auth()->lastName(), auth()->email(), auth()->scopes(), auth()->scopesArray(), ]; });
注意:默认情况下,auth() 使用默认驱动。如果您未将 jwt 设置为默认驱动,那么您需要在先前的使用示例中调用 auth('jwt')
测试
您可以为测试生成 JWT 令牌。它将使用测试文件夹中的 private_key 生成,并将与同一文件夹中的 public_key 进行比较。 示例
use Tests\TestCase; use Supaapps\Guard\Tests\Concerns\GenerateJwtToken; class CustomTest extends TestCase { use GenerateJwtToken; public function testThatIAmActingAsUser(): void { $user = User::factory()->create(); $this->withAccessTokenFor($user); $this->assertTrue(auth('jwt')->check()); $this->assertTrue($user->id, auth('jwt')->id()); } }
HTTP 测试
withAccessTokenFor 方法将 Bearer 令牌添加到由 http 测试发送的 headers 中。但是,您需要在您的测试中某处指定服务器 URL。例如,tests/CreatesApplication
<?php use Supaapps\Guard\Tests\Concerns\GenerateJwtToken; trait CreatesApplication { use GenerateJwtToken; public function createApplication(): Application { ... $this->setAuthServerUrl(); return $app; } }
接下来运行您的 http 测试,例如
<?php namespace Tests\Feature; use Tests\TestCase; class CustomTest extends TestCase { public function itReturnsTheAuthUser(): void { $user = User::factory()->create(); $this->withAccessTokenFor($user); // assume you have /user endpoint that // - uses auth:jwt middleware // - and returns auth user $response = $this->getJson('/user'); $response->assertOk() ->assertJson($user->toArray()); } }