我正在使用Laravel Passport来保护我的REST API。目前,我使用$user->createToken('APP_NAME')->accessToken
创建个人访问令牌,但这些令牌没有到期日期。所以我想创建一个密码访问令牌。我注意到,这些是由AccessTokenController.issueToken()
方法生成的。
但是我找不到任何关于如何调用它的信息。
我目前的解决方案
$input = $request->all();
$user = User::where('email', $input['email'])->first();
if ($user) {
if ($input['password'] == $user->password) {
$token = $user->createToken($this->app_name)->accessToken;
return [
'token' => $token,
'user' => $user
];
} else
return new ResponseGeneratorError('Password mismatch', 400);
} else
return new ResponseGeneratorError('User does not exist', 400);
答案 0 :(得分:0)
我找到了解决方案here:
<?php
namespace App\Traits;
use App\User;
use DateTime;
use GuzzleHttp\Psr7\Response;
use Illuminate\Events\Dispatcher;
use Laravel\Passport\Bridge\AccessToken;
use Laravel\Passport\Bridge\AccessTokenRepository;
use Laravel\Passport\Bridge\Client;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Passport;
use Laravel\Passport\TokenRepository;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
# https://github.com/laravel/passport/issues/71
/**
* Trait PassportToken
*
* @package App\Traits
*/
trait PassportToken {
/**
* Generate a new unique identifier.
*
* @param int $length
*
* @throws OAuthServerException
*
* @return string
*/
private function generateUniqueIdentifier($length = 40) {
try {
return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (\TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred');
} catch (\Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred');
} catch (\Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string');
}
// @codeCoverageIgnoreEnd
}
private function issueRefreshToken(AccessTokenEntityInterface $accessToken) {
$maxGenerationAttempts = 10;
$refreshTokenRepository = app(RefreshTokenRepository::class);
$refreshToken = $refreshTokenRepository->getNewRefreshToken();
$refreshToken->setExpiryDateTime((new \DateTime())->add(Passport::refreshTokensExpireIn()));
$refreshToken->setAccessToken($accessToken);
while ($maxGenerationAttempts-- > 0) {
$refreshToken->setIdentifier($this->generateUniqueIdentifier());
try {
$refreshTokenRepository->persistNewRefreshToken($refreshToken);
return $refreshToken;
} catch (UniqueTokenIdentifierConstraintViolationException $e) {
if ($maxGenerationAttempts === 0) {
throw $e;
}
}
}
}
protected function createPassportTokenByUser(User $user, $clientId) {
$accessToken = new AccessToken($user->id);
$accessToken->setIdentifier($this->generateUniqueIdentifier());
$accessToken->setClient(new Client($clientId, null, null));
$accessToken->setExpiryDateTime((new DateTime())->add(Passport::tokensExpireIn()));
$accessTokenRepository = new AccessTokenRepository(new TokenRepository(), new Dispatcher());
$accessTokenRepository->persistNewAccessToken($accessToken);
$refreshToken = $this->issueRefreshToken($accessToken);
return [
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
];
}
protected function sendBearerTokenResponse($accessToken, $refreshToken) {
$response = new BearerTokenResponse();
$response->setAccessToken($accessToken);
$response->setRefreshToken($refreshToken);
$privateKey = new CryptKey('file://' . Passport::keyPath('oauth-private.key'), null, false);
$response->setPrivateKey($privateKey);
$response->setEncryptionKey(app('encrypter')->getKey());
return $response->generateHttpResponse(new Response);
}
/**
* @param \App\User $user
* @param $clientId
* @param bool $output default = true
* @return array | \League\OAuth2\Server\ResponseTypes\BearerTokenResponse
*/
protected function getBearerTokenByUser(User $user, $clientId, $output = true) {
$passportToken = $this->createPassportTokenByUser($user, $clientId);
$bearerToken = $this->sendBearerTokenResponse($passportToken['access_token'], $passportToken['refresh_token']);
if (!$output) {
$bearerToken = json_decode($bearerToken->getBody()->__toString(), true);
}
return $bearerToken;
}
}
我将new CryptKey('file://' . Passport::keyPath('oauth-private.key'))
更改为new CryptKey('file://' . Passport::keyPath('oauth-private.key'), null, false)
以避免权限不正确错误(从here修复)