我只是用过laravel-passport,它和jwt auth一样。
我想向我的accessToken添加一些自定义声明,这可能吗?
我想在访问令牌和API调用时传递
2fa_status => true
使用此访问令牌,我也希望从令牌获得该声明。
例如(预期的代币索偿)
{
"aud": "7",
"jti": "123",
"iat": 1568368682,
"nbf": 1568368682,
"exp": 1599991082,
"sub": "2",
"scopes": [],
"2fa_status": false
}
我正在生成令牌,如下所示:
$tokenResult = $user->createToken('Personal Access Token');
答案 0 :(得分:0)
有可能
将此添加到AuthServiceProvider
Passport::routes();
Passport::personalAccessClientId(1); //<-- this 1 is id of your personal key
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
现在您可以像这样创建新令牌
$user->createToken('email')->accessToken; // you can change email to any for remember why this code generated like social facebook
根据documents添加更多参数,请尝试
$user->createToken('email', ['extra' => 'params'])->accessToken;
希望这会有所帮助
答案 1 :(得分:0)
认为您可以做的事情与该问题的答案非常相似: Customising token response Laravel Passport
在您自己的BearerTokenResponse类中,重写generateHttpResponse方法,在其中,您可以在访问令牌中添加任何内容,然后再将其转换为JWT:
public function generateHttpResponse(ResponseInterface $response)
{
$expireDateTime = $this->accessToken->getExpiryDateTime()->getTimestamp();
// add custom claims here, ie. $this->accessToken->withClaim('name', 'value');
$jwtAccessToken = $this->accessToken->convertToJWT($this->privateKey);
...
答案 2 :(得分:0)
我处于类似情况,但是我使用了密码授予客户端在身份验证过程中向用户颁发令牌,我需要使用用户的个人访问令牌为自己生成一个访问令牌,以供其在第三方应用程序中使用。您可以通过更新范围来解决此问题。我还需要验证用户是否通过了2fa。
在您的
中AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Passport::routes(function ($router) {
$router->forAccessTokens();
$router->forPersonalAccessTokens();
$router->forTransientTokens(); // register the transient token. skip if all routes are enabled
});
// Add scope to verify the user
// take note that here 2 scope for this due to refresh token scope
Passport::tokensCan([
'2fa-pass' => '2FA Pass',
'2fa-not-pass' => '2FA Pass',
]);
}
下一步是您的身份验证过程,您在其中发送密码授予类型
// I'm using route::dispatch to do a proxy request
// you can use Guzzle if you want
$request->request->add([
'grant_type' => 'password',
'client_id' => 'client-id',
client_secret' => 'client-secret',
'username' => $credentials['email'],
'password' => $credentials['password'],
'scope' => '2fa-not-pass 2fa-pass' // take note that I added the two scope here
]);
$tokenRequest = Request::create('/oauth/token', 'POST');
$response = \Route::dispatch($tokenRequest);
然后在您的2FA验证过程中
// your process of verifying the 2FA code
// after that you need to update the scope by doing a refresh token
$request->request->add([
'grant_type' => 'refresh_token',
'refresh_token' => $request->input('refresh_token'),
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'scope' => '2fa-pass' // I removed the 2fa-not-pass in refreshing the token
]);
$tokenRequest = Request::create('/oauth/token', 'POST');
$response = \Route::dispatch($tokenRequest);
请注意有关范围,刷新令牌时,只能获得与原始访问令牌相同或更窄的范围。如果尝试获取原始访问令牌未提供的范围,则会收到错误消息。 -爱国者
在此处回答:https://stackoverflow.com/a/45856634/11537130
请注意,这将生成具有新范围的新令牌