如何从JWT access_token中提取user_id(bshaffer oauth库)

时间:2017-11-03 15:13:26

标签: php authentication oauth-2.0 jwt

我遵循了JWT教程https://bshaffer.github.io/oauth2-server-php-docs/overview/jwt-access-tokens/

我创建了access_token,如下所示:

$publicKey  = file_get_contents(dirname(__FILE__) .'/Keys/pubkey.pem');
$privateKey = file_get_contents(dirname(__FILE__) .'/Keys/privkey.pem');

// create storage
$storage = new \OAuth2\Storage\Memory([
    'keys' => [
        'public_key'  => $publicKey,
        'private_key' => $privateKey,
    ],
    'client_credentials' => [
        'api' => ['client_secret' => 'secret']
    ],
]);

$server = new \OAuth2\Server($storage, array(
    'use_jwt_access_tokens' => true,
));
$server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));

$tokenData = json_decode($server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->getResponseBody(), true);

回复是

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpZCI6IjM1NWM5YjEzNjRkNmUzMmM2YTM0YWQ2NDgzMWM2NzZjZjllYmEyZGIiLCJqdGkiOiIzNTVjOWIxMzY0ZDZlMzJjNmEzNGFkNjQ4MzFjNjc2Y2Y5ZWJhMmRiIiwiaXNzIjoiIiwiYXVkIjoiYXBpIiwic3ViIjpudWxsLCJleHAiOjE1MDk3MjQ5NDYsImlhdCI6MTUwOTcyMTM0NiwidG9rZW5fdHlwZSI6ImJlYXJlciIsInNjb3BlIjpudWxsfQ.QzCb-nFYHaiJQcj8NsiAN8WoPo24MC5xIgNxWCCNO1WCPzJ_iZ7In6YWcdfe3xVcJQRUzECrveYmKFZizVf7P2UYeGiZjd0tUqM972YiF_9ZrIEjVN_L9QSfGCCAQlhCvXFUdWrfMyiLjUi4D4LYELKyPpkDrJ-0QG5ngtBX_-Iy2zH7BaXf_AGAIyJPScdVvhs_4trroWSaJn7I8KRMtihZCV6ucAUVjkiXJ5rL6Pyem--3PRXJX6IoOQtbKUyRxwhUZfHefPHWaHUdwJY3f83gRnJrSfXql0KdF5i1SdUf1VGwEldmdHPnGHCfKKVypjeXzaP9lHqeO63CXVeY2A",
    "expires_in": 3600,
    "token_type": "bearer",
    "scope": null,
}

现在我可以按如下方式验证令牌

$publicKey  = file_get_contents(dirname(__FILE__) .'/Keys/pubkey.pem');

// no private key necessary
    $keyStorage = new \OAuth2\Storage\Memory(array('keys' => array(
'public_key'  => $publicKey,
)));

$server = new \OAuth2\Server($keyStorage, array(
    'use_jwt_access_tokens' => true,
));
$validation = $server->verifyResourceRequest(\OAuth2\Request::createFromGlobals());

if (!$validation) {
    $server->getResponse()->send();
    die;
}

所以它验证了令牌,但我找不到提取user_id的方法 - 或者" sub" - 根据教程有效文档

{
  "id": "394a71988caa6cc30601e43f5b6569d52cd7f6df",
  "jti": "394a71988caa6cc30601e43f5b6569d52cd7f6df",
  "iss": "issuer_id",
  "aud": "client_id",
  "sub": "user_id",
  "exp": 1483711650,
  "iat": 1483708050,
  "token_type": "bearer",
  "scope": "onescope twoscope"
}

我希望从有效令牌(通过标头)中获取user_id,并使用它从我的数据库中收集相关的用户数据。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

我能够按照本指南实现所需的功能:https://bshaffer.github.io/oauth2-server-php-docs/grant-types/jwt-bearer/

答案 1 :(得分:0)

好吧,既然您说您已经成功完成了以下步骤:

$validation = $server->verifyResourceRequest(\OAuth2\Request::createFromGlobals());
if (!$validation) 
{
  $server->getResponse()->send();
  die;
 }

这意味着已经发出了一个有效的访问令牌,该令牌存储在某个位置,现在供客户端使用,然后您可以像这样轻松地检索关联的user_id:

  $token = $server->getAccessTokenData( $request->createFromGlobals() );
  print_r( "The associated userid with this token is {$token['user_id']}" );

否则,成功创建访问令牌后,您就可以像这样拆分它:

$tokenData = json_decode($server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->getResponseBody(), true); //here you have the response body as a string and make it a php object
$separator = '.';

list($header, $payload, $signature) = explode($separator, $tokenData->access_token);
//In your case you need only $payload but it's a copy paste from my code testI
$payloadAsString = base64_decode($payload);
$payloadAsObject = json_decode($payloadAsString);
$tokenData->sub = $payloadAsObject->sub ; // Add a new property to your $tokenData object

现在$ tokenData中有子(user_id)。您可以随心所欲地做。 Json_decode等等,或用它来查询数据库用户的表。

希望对某人有所帮助。