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