feat: support bearer authorization

This commit is contained in:
FoskyM 2023-10-02 05:40:58 +08:00
parent b66e8a56d1
commit a92398ca8d
No known key found for this signature in database
GPG key ID: 42C0ED6994AD7E9C

View file

@ -9,6 +9,7 @@ use Flarum\User\User;
use FoskyM\OAuthCenter\OAuth; use FoskyM\OAuthCenter\OAuth;
use FoskyM\OAuthCenter\Storage; use FoskyM\OAuthCenter\Storage;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Laminas\Diactoros\Response\JsonResponse; use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
@ -20,6 +21,7 @@ use FoskyM\OAuthCenter\Models\Scope;
class ResourceScopeMiddleware implements MiddlewareInterface class ResourceScopeMiddleware implements MiddlewareInterface
{ {
const TOKEN_PREFIX = 'Bearer ';
protected $settings; protected $settings;
public function __construct(SettingsRepositoryInterface $settings) public function __construct(SettingsRepositoryInterface $settings)
{ {
@ -31,8 +33,17 @@ class ResourceScopeMiddleware implements MiddlewareInterface
return $handler->handle($request); return $handler->handle($request);
} }
$path = $request->getAttribute('originalUri')->getPath(); $headerLine = $request->getHeaderLine('authorization');
$parts = explode(';', $headerLine);
if (isset($parts[0]) && Str::startsWith($parts[0], self::TOKEN_PREFIX)) {
$token = substr($parts[0], strlen(self::TOKEN_PREFIX));
} else {
$token = Arr::get($request->getQueryParams(), 'access_token', ''); $token = Arr::get($request->getQueryParams(), 'access_token', '');
}
$path = $request->getAttribute('originalUri')->getPath();
if ($token !== '' && $scope = Scope::get_path_scope($path)) { if ($token !== '' && $scope = Scope::get_path_scope($path)) {
if (strtolower($request->getMethod()) === strtolower($scope->method)) { if (strtolower($request->getMethod()) === strtolower($scope->method)) {
try { try {