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