97 lines
3.1 KiB
PHP
97 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Providers;
|
|
|
|
use App\Logic\OpenIDLogic;
|
|
use App\Models\User;
|
|
use Exception;
|
|
use Firebase\JWT\JWK;
|
|
use Firebase\JWT\JWT;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\ServiceProvider;
|
|
use stdClass;
|
|
|
|
class AppServiceProvider extends ServiceProvider
|
|
{
|
|
/**
|
|
* Register any application services.
|
|
*/
|
|
public function register(): void
|
|
{
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Bootstrap any application services.
|
|
*/
|
|
public function boot(): void
|
|
{
|
|
$this->setJWTGuard();
|
|
}
|
|
|
|
private function setJWTGuard(): void
|
|
{
|
|
Auth::viaRequest('jwt', function (Request $request) {
|
|
$logic = app(OpenIDLogic::class);
|
|
|
|
$keys = JWK::parseKeySet($logic->jwks);
|
|
|
|
$jwt = $request->bearerToken();
|
|
|
|
if (empty($jwt)) {
|
|
return null;
|
|
// return response()->json(['error' => 'No token provided'], 401);
|
|
}
|
|
|
|
$headers = new stdClass();
|
|
|
|
try {
|
|
$decoded = JWT::decode($jwt, $keys, $headers);
|
|
// $request->attributes->add(['token_type' => $headers->typ]);
|
|
} catch (Exception $e) {
|
|
// dd($e);
|
|
return null;
|
|
|
|
// return response()->json(['error' => 'Invalid token, '.$e->getMessage()], 401);
|
|
}
|
|
|
|
// must id_token
|
|
if ($headers->typ !== 'id_token') {
|
|
return null;
|
|
|
|
// return response()->json(['error' => 'The token not id_token'], 401);
|
|
}
|
|
|
|
// 检查是否有 字段
|
|
$required_fields = [
|
|
'name', 'sub',
|
|
];
|
|
|
|
foreach ($required_fields as $field) {
|
|
if (! isset($decoded->$field)) {
|
|
return null;
|
|
|
|
// return response()->json(['error' => 'The token not contain the field '.$field], 401);
|
|
}
|
|
}
|
|
|
|
if (config('oauth.force_aud')) {
|
|
if (! in_array($decoded->aud, config('oauth.trusted_aud'))) {
|
|
throw new Exception('The application rejected the token, token aud is '.$decoded->aud.', app aud is '.config('oauth.client_id'));
|
|
// return response()->json(['error' => 'The application rejected the token, token aud is '.$decoded->aud.', app aud is '.config('oauth.client_id')], 401);
|
|
}
|
|
|
|
// throw
|
|
throw new Exception('The token not match the application, '.' token aud is '.$decoded->aud.', app aud is '.config('oauth.client_id'));
|
|
// return response()->json(['error' => 'The token not match the application, '.' token aud is '.$decoded->aud.', app aud is '.config('oauth.client_id')], 401);
|
|
}
|
|
|
|
return User::where('external_id', $decoded->sub)->firstOrCreate([
|
|
'external_id' => $decoded->sub,
|
|
'name' => $decoded->name,
|
|
]);
|
|
});
|
|
}
|
|
}
|