]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/OpenIdService.php
Token expiration and refreshing using the refresh_token flow
[bookstack] / app / Auth / Access / OpenIdService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\OpenIdException;
6 use BookStack\Exceptions\UserRegistrationException;
7 use Exception;
8 use Lcobucci\JWT\Token;
9 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
10 use OpenIDConnectClient\AccessToken;
11 use OpenIDConnectClient\OpenIDConnectProvider;
12
13 /**
14  * Class OpenIdService
15  * Handles any app-specific OpenId tasks.
16  */
17 class OpenIdService extends ExternalAuthService
18 {
19     protected $config;
20
21     /**
22      * OpenIdService constructor.
23      */
24     public function __construct(RegistrationService $registrationService, User $user)
25     {
26         parent::__construct($registrationService, $user);
27         
28         $this->config = config('openid');
29     }
30
31     /**
32      * Initiate a authorization flow.
33      * @throws Error
34      */
35     public function login(): array
36     {
37         $provider = $this->getProvider();
38         return [
39             'url' => $provider->getAuthorizationUrl(),
40             'state' => $provider->getState(),
41         ];
42     }
43
44     /**
45      * Initiate a logout flow.
46      * @throws Error
47      */
48     public function logout(): array
49     {
50         $this->actionLogout();
51         $url = '/';
52         $id = null;
53
54         return ['url' => $url, 'id' => $id];
55     }
56
57     /**
58      * Refresh the currently logged in user.
59      * @throws Error
60      */
61     public function refresh(): bool
62     {
63         // Retrieve access token for current session
64         $json = session()->get('openid_token');
65         $accessToken = new AccessToken(json_decode($json, true));
66
67         // Check whether the access token or ID token is expired
68         if (!$accessToken->getIdToken()->isExpired() && !$accessToken->hasExpired()) {
69             return true;
70         }
71
72         // If no refresh token available, logout
73         if ($accessToken->getRefreshToken() === null) {
74             $this->actionLogout();
75             return false;
76         }
77
78         // ID token or access token is expired, we refresh it using the refresh token
79         try {
80             $provider = $this->getProvider();
81
82             $accessToken = $provider->getAccessToken('refresh_token', [
83                 'refresh_token' => $accessToken->getRefreshToken(),
84             ]);
85         } catch (IdentityProviderException $e) {
86             // Refreshing failed, logout
87             $this->actionLogout();
88             return false;
89         }
90
91         // A valid token was obtained, we update the access token
92         session()->put('openid_token', json_encode($accessToken));
93
94         return true;
95     }
96
97     /**
98      * Process the Authorization response from the authorization server and
99      * return the matching, or new if registration active, user matched to
100      * the authorization server.
101      * Returns null if not authenticated.
102      * @throws Error
103      * @throws OpenIdException
104      * @throws ValidationError
105      * @throws JsonDebugException
106      * @throws UserRegistrationException
107      */
108     public function processAuthorizeResponse(?string $authorizationCode): ?User
109     {
110         $provider = $this->getProvider();
111
112         // Try to exchange authorization code for access token
113         $accessToken = $provider->getAccessToken('authorization_code', [
114             'code' => $authorizationCode,
115         ]);
116
117         return $this->processAccessTokenCallback($accessToken);
118     }
119
120     /**
121      * Do the required actions to log a user out.
122      */
123     protected function actionLogout()
124     {
125         auth()->logout();
126         session()->invalidate();
127     }
128
129     /**
130      * Load the underlying OpenID Connect Provider.
131      * @throws Error
132      * @throws Exception
133      */
134     protected function getProvider(): OpenIDConnectProvider
135     {
136         $settings = $this->config['openid'];
137         $overrides = $this->config['openid_overrides'] ?? [];
138
139         if ($overrides && is_string($overrides)) {
140             $overrides = json_decode($overrides, true);
141         }
142
143         $openIdSettings = $this->loadOpenIdDetails();
144         $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
145
146         $signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
147         return new OpenIDConnectProvider($settings, ['signer' => $signer]);
148     }
149
150     /**
151      * Load dynamic service provider options required by the onelogin toolkit.
152      */
153     protected function loadOpenIdDetails(): array
154     {
155         return [
156             'redirectUri' => url('/openid/redirect'),
157         ];
158     }
159
160     /**
161      * Calculate the display name
162      */
163     protected function getUserDisplayName(Token $token, string $defaultValue): string
164     {
165         $displayNameAttr = $this->config['display_name_attributes'];
166
167         $displayName = [];
168         foreach ($displayNameAttr as $dnAttr) {
169             $dnComponent = $token->getClaim($dnAttr, '');
170             if ($dnComponent !== '') {
171                 $displayName[] = $dnComponent;
172             }
173         }
174
175         if (count($displayName) == 0) {
176             $displayName = $defaultValue;
177         } else {
178             $displayName = implode(' ', $displayName);
179         }
180
181         return $displayName;
182     }
183
184     /**
185      * Get the value to use as the external id saved in BookStack
186      * used to link the user to an existing BookStack DB user.
187      */
188     protected function getExternalId(Token $token, string $defaultValue)
189     {
190         $userNameAttr = $this->config['external_id_attribute'];
191         if ($userNameAttr === null) {
192             return $defaultValue;
193         }
194
195         return $token->getClaim($userNameAttr, $defaultValue);
196     }
197
198     /**
199      * Extract the details of a user from an ID token.
200      */
201     protected function getUserDetails(Token $token): array
202     {
203         $email = null;
204         $emailAttr = $this->config['email_attribute'];
205         if ($token->hasClaim($emailAttr)) {
206             $email = $token->getClaim($emailAttr);
207         }
208
209         return [
210             'external_id' => $token->getClaim('sub'),
211             'email' => $email,
212             'name' => $this->getUserDisplayName($token, $email),
213         ];
214     }
215
216     /**
217      * Processes a received access token for a user. Login the user when
218      * they exist, optionally registering them automatically.
219      * @throws OpenIdException
220      * @throws JsonDebugException
221      * @throws UserRegistrationException
222      */
223     public function processAccessTokenCallback(AccessToken $accessToken): User
224     {
225         $userDetails = $this->getUserDetails($accessToken->getIdToken());
226         $isLoggedIn = auth()->check();
227
228         if ($this->config['dump_user_details']) {
229             throw new JsonDebugException($accessToken->jsonSerialize());
230         }
231
232         if ($userDetails['email'] === null) {
233             throw new OpenIdException(trans('errors.openid_no_email_address'));
234         }
235
236         if ($isLoggedIn) {
237             throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
238         }
239
240         $user = $this->getOrRegisterUser($userDetails);
241         if ($user === null) {
242             throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
243         }
244
245         auth()->login($user);
246         session()->put('openid_token', json_encode($accessToken));
247         return $user;
248     }
249 }