]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Oidc/OidcService.php
Fixes padding issues of the sidebar's items
[bookstack] / app / Auth / Access / Oidc / OidcService.php
1 <?php
2
3 namespace BookStack\Auth\Access\Oidc;
4
5 use function auth;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\RegistrationService;
8 use BookStack\Auth\User;
9 use BookStack\Exceptions\JsonDebugException;
10 use BookStack\Exceptions\OpenIdConnectException;
11 use BookStack\Exceptions\StoppedAuthenticationException;
12 use BookStack\Exceptions\UserRegistrationException;
13 use function config;
14 use Exception;
15 use Illuminate\Support\Facades\Cache;
16 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
17 use Psr\Http\Client\ClientExceptionInterface;
18 use Psr\Http\Client\ClientInterface as HttpClient;
19 use function trans;
20 use function url;
21
22 /**
23  * Class OpenIdConnectService
24  * Handles any app-specific OIDC tasks.
25  */
26 class OidcService
27 {
28     protected $registrationService;
29     protected $loginService;
30     protected $httpClient;
31
32     /**
33      * OpenIdService constructor.
34      */
35     public function __construct(RegistrationService $registrationService, LoginService $loginService, HttpClient $httpClient)
36     {
37         $this->registrationService = $registrationService;
38         $this->loginService = $loginService;
39         $this->httpClient = $httpClient;
40     }
41
42     /**
43      * Initiate an authorization flow.
44      *
45      * @return array{url: string, state: string}
46      */
47     public function login(): array
48     {
49         $settings = $this->getProviderSettings();
50         $provider = $this->getProvider($settings);
51
52         return [
53             'url'   => $provider->getAuthorizationUrl(),
54             'state' => $provider->getState(),
55         ];
56     }
57
58     /**
59      * Process the Authorization response from the authorization server and
60      * return the matching, or new if registration active, user matched to
61      * the authorization server.
62      * Returns null if not authenticated.
63      *
64      * @throws Exception
65      * @throws ClientExceptionInterface
66      */
67     public function processAuthorizeResponse(?string $authorizationCode): ?User
68     {
69         $settings = $this->getProviderSettings();
70         $provider = $this->getProvider($settings);
71
72         // Try to exchange authorization code for access token
73         $accessToken = $provider->getAccessToken('authorization_code', [
74             'code' => $authorizationCode,
75         ]);
76
77         return $this->processAccessTokenCallback($accessToken, $settings);
78     }
79
80     /**
81      * @throws OidcIssuerDiscoveryException
82      * @throws ClientExceptionInterface
83      */
84     protected function getProviderSettings(): OidcProviderSettings
85     {
86         $config = $this->config();
87         $settings = new OidcProviderSettings([
88             'issuer'                => $config['issuer'],
89             'clientId'              => $config['client_id'],
90             'clientSecret'          => $config['client_secret'],
91             'redirectUri'           => url('/oidc/callback'),
92             'authorizationEndpoint' => $config['authorization_endpoint'],
93             'tokenEndpoint'         => $config['token_endpoint'],
94         ]);
95
96         // Use keys if configured
97         if (!empty($config['jwt_public_key'])) {
98             $settings->keys = [$config['jwt_public_key']];
99         }
100
101         // Run discovery
102         if ($config['discover'] ?? false) {
103             $settings->discoverFromIssuer($this->httpClient, Cache::store(null), 15);
104         }
105
106         $settings->validate();
107
108         return $settings;
109     }
110
111     /**
112      * Load the underlying OpenID Connect Provider.
113      */
114     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
115     {
116         return new OidcOAuthProvider($settings->arrayForProvider(), [
117             'httpClient'     => $this->httpClient,
118             'optionProvider' => new HttpBasicAuthOptionProvider(),
119         ]);
120     }
121
122     /**
123      * Calculate the display name.
124      */
125     protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
126     {
127         $displayNameAttr = $this->config()['display_name_claims'];
128
129         $displayName = [];
130         foreach ($displayNameAttr as $dnAttr) {
131             $dnComponent = $token->getClaim($dnAttr) ?? '';
132             if ($dnComponent !== '') {
133                 $displayName[] = $dnComponent;
134             }
135         }
136
137         if (count($displayName) == 0) {
138             $displayName[] = $defaultValue;
139         }
140
141         return implode(' ', $displayName);
142     }
143
144     /**
145      * Extract the details of a user from an ID token.
146      *
147      * @return array{name: string, email: string, external_id: string}
148      */
149     protected function getUserDetails(OidcIdToken $token): array
150     {
151         $id = $token->getClaim('sub');
152
153         return [
154             'external_id' => $id,
155             'email'       => $token->getClaim('email'),
156             'name'        => $this->getUserDisplayName($token, $id),
157         ];
158     }
159
160     /**
161      * Processes a received access token for a user. Login the user when
162      * they exist, optionally registering them automatically.
163      *
164      * @throws OpenIdConnectException
165      * @throws JsonDebugException
166      * @throws UserRegistrationException
167      * @throws StoppedAuthenticationException
168      */
169     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
170     {
171         $idTokenText = $accessToken->getIdToken();
172         $idToken = new OidcIdToken(
173             $idTokenText,
174             $settings->issuer,
175             $settings->keys,
176         );
177
178         if ($this->config()['dump_user_details']) {
179             throw new JsonDebugException($idToken->getAllClaims());
180         }
181
182         try {
183             $idToken->validate($settings->clientId);
184         } catch (OidcInvalidTokenException $exception) {
185             throw new OpenIdConnectException("ID token validate failed with error: {$exception->getMessage()}");
186         }
187
188         $userDetails = $this->getUserDetails($idToken);
189         $isLoggedIn = auth()->check();
190
191         if (empty($userDetails['email'])) {
192             throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
193         }
194
195         if ($isLoggedIn) {
196             throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
197         }
198
199         $user = $this->registrationService->findOrRegister(
200             $userDetails['name'],
201             $userDetails['email'],
202             $userDetails['external_id']
203         );
204
205         if ($user === null) {
206             throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
207         }
208
209         $this->loginService->login($user, 'oidc');
210
211         return $user;
212     }
213
214     /**
215      * Get the OIDC config from the application.
216      */
217     protected function config(): array
218     {
219         return config('oidc');
220     }
221 }