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