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