Получение ошибки «unsupported_grant_type» при реализации специального гранта OAuth2Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Получение ошибки «unsupported_grant_type» при реализации специального гранта OAuth2

Сообщение Anonymous »

Я пытаюсь реализовать собственный тип предоставления OAuth2 в Laravel Passport для мобильной аутентификации, но сталкиваюсь со следующей ошибкой

Код: Выделить всё

{
"error": "unsupported_grant_type",
"error_description": "The authorization grant type is not supported by the authorization server."
}
Вот пользовательский класс MobileGrant, который я использую:

Код: Выделить всё

namespace App\Grants;

use App\Enums\UserType;
use Laravel\Passport\Bridge\UserRepository;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Bridge\AccessToken;
use League\OAuth2\Server\Grant\AbstractGrant;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ServerRequestInterface;
use DateInterval;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class MobileGrant extends AbstractGrant
{
public function __construct(UserRepository $userRepository, RefreshTokenRepository $refreshTokenRepository)
{
$this->setUserRepository($userRepository);
$this->setRefreshTokenRepository($refreshTokenRepository);
}

public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
DateInterval $accessTokenTTL
) {
$mobile = $this->getRequestParameter('mobile', $request);
$confirmCode = $this->getRequestParameter('mobile_confirm_code', $request);

if (!$mobile || !$confirmCode) {
return response()->json(['message' => 'Mobile number and confirmation code are required.'], 400);
}

$user = User::where('mobile', $mobile)->first();

if (User::where(['mobile' => $mobile, 'mobile_confirm_code' => $confirmCode])->exists() || $confirmCode == "1234") {
if (!self::isExpiredConfirmCode($user)) {
if (User::where(['mobile' => $mobile])->whereNull('mobile_verified_at')->exists()) {
User::where('mobile', $mobile)->update([
'mobile_verified_at' => Carbon::now()->format('Y-m-d H:i:s')
]);
}

Auth::login($user);
$role = UserType::hasValue($user->role) ? $user->role : null;

$accessToken = $this->issueAccessToken($accessTokenTTL, $user->id, $role);
$refreshToken = $this->issueRefreshToken($accessToken);

return [
'token_type' => 'Bearer',
'expires_in' => $accessTokenTTL->s,
'access_token' => (string) $accessToken,
'refresh_token' => (string) $refreshToken,
];
} else {
return response()->json(['message' => 'Confirmation code expired.'], 400);
}
} else {
return response()->json(['message' =>  'Invalid confirmation code.'], 400);
}
}

public function getIdentifier()
{
return 'mobile';
}

public function isExpiredConfirmCode($user)
{
return Carbon::parse($user->expire_mobile_confirm_code)->lt(Carbon::now());
}
}

В моем AppServiceProvider я включаю пользовательский тип предоставления:

Код: Выделить всё

public function boot(): void
{
app(AuthorizationServer::class)->enableGrantType(
new MobileGrant(
app()->make(\Laravel\Passport\Bridge\UserRepository::class),
app()->make(\Laravel\Passport\Bridge\RefreshTokenRepository::class)
),
new \DateInterval('P1Y') // Access token expiration time
);
}
Однако, когда я пытаюсь запросить токен со следующими данными:

Код: Выделить всё

{
"grant_type": "mobile",
"client_id": "client-id-here",
"client_secret": "client-secret-here",
"mobile": "mobileNumber",
"mobile_confirm_code": "1234",
"scope": ""
}
Я получаю сообщение об ошибке unsupported_grant_type.
Может ли кто-нибудь помочь мне понять, почему возникает эта ошибка и как ее устранить? Я включил пользовательский тип гранта в AppServiceProvider, но он по-прежнему не работает.
Заранее спасибо!
Получаю ошибку «unsupported_grant_type» при реализации собственный грант OAuth2 в Laravel Passport.
Я выполнял различные попытки отладки, но не смог прийти к какому-либо выводу. Я зарегистрировал данные запроса в mobileGrant, и данные прошли правильно.
Я также уверен, что идентификатор клиента и секретная информация клиента верны.

Код: Выделить всё

 public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
DateInterval $accessTokenTTL
) {
dd($request);
}
В некоторых документах упоминается, что паспорт::routes() также следует добавить, но в последней документации Passport указано, что в этом нет необходимости.

Подробнее здесь: https://stackoverflow.com/questions/793 ... uth2-grant
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»