blob: 6ccacd6d9cf0708324019d79b7a60036ee816f50 [file] [log] [blame]
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +01001<?php
2
3namespace OAuth2\Storage;
4
5use OAuth2\Encryption\EncryptionInterface;
6use OAuth2\Encryption\Jwt;
7
8/**
9 * @author Brent Shaffer <bshafs at gmail dot com>
10 */
11class JwtAccessToken implements JwtAccessTokenInterface
12{
13 protected $publicKeyStorage;
14 protected $tokenStorage;
15 protected $encryptionUtil;
16
17 /**
18 * @param OAuth2\Encryption\PublicKeyInterface $publicKeyStorage the public key encryption to use
19 * @param OAuth2\Storage\AccessTokenInterface $tokenStorage OPTIONAL persist the access token to another storage. This is useful if
20 * you want to retain access token grant information somewhere, but
21 * is not necessary when using this grant type.
22 * @param OAuth2\Encryption\EncryptionInterface $encryptionUtil OPTIONAL class to use for "encode" and "decode" functions.
23 */
24 public function __construct(PublicKeyInterface $publicKeyStorage, AccessTokenInterface $tokenStorage = null, EncryptionInterface $encryptionUtil = null)
25 {
26 $this->publicKeyStorage = $publicKeyStorage;
27 $this->tokenStorage = $tokenStorage;
28 if (is_null($encryptionUtil)) {
29 $encryptionUtil = new Jwt;
30 }
31 $this->encryptionUtil = $encryptionUtil;
32 }
33
34 public function getAccessToken($oauth_token)
35 {
36 // just decode the token, don't verify
37 if (!$tokenData = $this->encryptionUtil->decode($oauth_token, null, false)) {
38 return false;
39 }
40
41 $client_id = isset($tokenData['aud']) ? $tokenData['aud'] : null;
42 $public_key = $this->publicKeyStorage->getPublicKey($client_id);
43 $algorithm = $this->publicKeyStorage->getEncryptionAlgorithm($client_id);
44
45 // now that we have the client_id, verify the token
46 if (false === $this->encryptionUtil->decode($oauth_token, $public_key, array($algorithm))) {
47 return false;
48 }
49
50 // normalize the JWT claims to the format expected by other components in this library
51 return $this->convertJwtToOAuth2($tokenData);
52 }
53
54 public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null)
55 {
56 if ($this->tokenStorage) {
57 return $this->tokenStorage->setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope);
58 }
59 }
60
61 public function unsetAccessToken($access_token)
62 {
63 if ($this->tokenStorage) {
64 return $this->tokenStorage->unsetAccessToken($access_token);
65 }
66 }
67
68
69 // converts a JWT access token into an OAuth2-friendly format
70 protected function convertJwtToOAuth2($tokenData)
71 {
72 $keyMapping = array(
73 'aud' => 'client_id',
74 'exp' => 'expires',
75 'sub' => 'user_id'
76 );
77
78 foreach ($keyMapping as $jwtKey => $oauth2Key) {
79 if (isset($tokenData[$jwtKey])) {
80 $tokenData[$oauth2Key] = $tokenData[$jwtKey];
81 unset($tokenData[$jwtKey]);
82 }
83 }
84
85 return $tokenData;
86 }
87}