]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/OpenIdConnect/OpenIdConnectService.php
Added token and key handling elements for oidc jwt
[bookstack] / app / Auth / Access / OpenIdConnect / OpenIdConnectService.php
1 <?php namespace BookStack\Auth\Access\OpenIdConnect;
2
3 use BookStack\Auth\Access\LoginService;
4 use BookStack\Auth\Access\OpenIdConnect\OpenIdConnectOAuthProvider;
5 use BookStack\Auth\Access\RegistrationService;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\JsonDebugException;
8 use BookStack\Exceptions\OpenIdConnectException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use Exception;
12 use Lcobucci\JWT\Token;
13 use League\OAuth2\Client\Token\AccessToken;
14 use function auth;
15 use function config;
16 use function dd;
17 use function trans;
18 use function url;
19
20 /**
21  * Class OpenIdConnectService
22  * Handles any app-specific OIDC tasks.
23  */
24 class OpenIdConnectService
25 {
26     protected $registrationService;
27     protected $loginService;
28     protected $config;
29
30     /**
31      * OpenIdService constructor.
32      */
33     public function __construct(RegistrationService $registrationService, LoginService $loginService)
34     {
35         $this->config = config('oidc');
36         $this->registrationService = $registrationService;
37         $this->loginService = $loginService;
38     }
39
40     /**
41      * Initiate an authorization flow.
42      * @return array{url: string, state: string}
43      */
44     public function login(): array
45     {
46         $provider = $this->getProvider();
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      */
60     public function processAuthorizeResponse(?string $authorizationCode): ?User
61     {
62         $provider = $this->getProvider();
63
64         // Try to exchange authorization code for access token
65         $accessToken = $provider->getAccessToken('authorization_code', [
66             'code' => $authorizationCode,
67         ]);
68
69         return $this->processAccessTokenCallback($accessToken);
70     }
71
72     /**
73      * Load the underlying OpenID Connect Provider.
74      */
75     protected function getProvider(): OpenIdConnectOAuthProvider
76     {
77         // Setup settings
78         $settings = [
79             'clientId' => $this->config['client_id'],
80             'clientSecret' => $this->config['client_secret'],
81             'redirectUri' => url('/oidc/redirect'),
82             'authorizationEndpoint' => $this->config['authorization_endpoint'],
83             'tokenEndpoint' => $this->config['token_endpoint'],
84         ];
85
86         return new OpenIdConnectOAuthProvider($settings);
87     }
88
89     /**
90      * Calculate the display name
91      */
92     protected function getUserDisplayName(Token $token, string $defaultValue): string
93     {
94         $displayNameAttr = $this->config['display_name_claims'];
95
96         $displayName = [];
97         foreach ($displayNameAttr as $dnAttr) {
98             $dnComponent = $token->claims()->get($dnAttr, '');
99             if ($dnComponent !== '') {
100                 $displayName[] = $dnComponent;
101             }
102         }
103
104         if (count($displayName) == 0) {
105             $displayName[] = $defaultValue;
106         }
107
108         return implode(' ', $displayName);
109     }
110
111     /**
112      * Extract the details of a user from an ID token.
113      * @return array{name: string, email: string, external_id: string}
114      */
115     protected function getUserDetails(Token $token): array
116     {
117         $id = $token->claims()->get('sub');
118         return [
119             'external_id' => $id,
120             'email' => $token->claims()->get('email'),
121             'name' => $this->getUserDisplayName($token, $id),
122         ];
123     }
124
125     /**
126      * Processes a received access token for a user. Login the user when
127      * they exist, optionally registering them automatically.
128      * @throws OpenIdConnectException
129      * @throws JsonDebugException
130      * @throws UserRegistrationException
131      * @throws StoppedAuthenticationException
132      */
133     protected function processAccessTokenCallback(OpenIdConnectAccessToken $accessToken): User
134     {
135         $idTokenText = $accessToken->getIdToken();
136         $idToken = new OpenIdConnectIdToken(
137             $idTokenText,
138             $this->config['issuer'],
139             [$this->config['jwt_public_key']]
140         );
141
142         // TODO - Create a class to manage token parsing and validation on this
143         // Ensure ID token validation is done:
144         // https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
145         // To full affect and tested
146         // JWT signature algorthims:
147         // https://datatracker.ietf.org/doc/html/rfc7518#section-3
148
149         $userDetails = $this->getUserDetails($accessToken->getIdToken());
150         $isLoggedIn = auth()->check();
151
152         if ($this->config['dump_user_details']) {
153             throw new JsonDebugException($accessToken->jsonSerialize());
154         }
155
156         if ($userDetails['email'] === null) {
157             throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
158         }
159
160         if ($isLoggedIn) {
161             throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
162         }
163
164         $user = $this->registrationService->findOrRegister(
165             $userDetails['name'], $userDetails['email'], $userDetails['external_id']
166         );
167
168         if ($user === null) {
169             throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
170         }
171
172         $this->loginService->login($user, 'oidc');
173         return $user;
174     }
175 }