|
21 | 21 | use HeadlessChromium\Dom\Node; |
22 | 22 | use HeadlessChromium\Dom\Selector\CssSelector; |
23 | 23 | use HeadlessChromium\Dom\Selector\Selector; |
| 24 | +use HeadlessChromium\Exception\AuthenticationFailed; |
24 | 25 | use HeadlessChromium\Exception\CommunicationException; |
25 | 26 | use HeadlessChromium\Exception\EvaluationFailed; |
26 | 27 | use HeadlessChromium\Exception\InvalidTimezoneId; |
@@ -160,6 +161,64 @@ public function getSession(): Session |
160 | 161 | return $this->target->getSession(); |
161 | 162 | } |
162 | 163 |
|
| 164 | + /** |
| 165 | + * Sets credentials to be used when the page encounters an HTTP authentication challenge. |
| 166 | + * |
| 167 | + * @throws AuthenticationFailed |
| 168 | + * @throws CommunicationException |
| 169 | + */ |
| 170 | + public function authenticate(string $username, string $password): void |
| 171 | + { |
| 172 | + $this->assertNotClosed(); |
| 173 | + |
| 174 | + $credentialsAttempted = false; |
| 175 | + |
| 176 | + $this->getSession()->on('method:Fetch.authRequired', function (array $params) use ($username, $password, &$credentialsAttempted) { |
| 177 | + if ($credentialsAttempted) { |
| 178 | + $this->getSession()->sendMessageSync( |
| 179 | + new Message('Fetch.continueWithAuth', [ |
| 180 | + 'requestId' => $params['requestId'], |
| 181 | + 'authChallengeResponse' => [ |
| 182 | + 'response' => 'CancelAuth', |
| 183 | + ], |
| 184 | + ]) |
| 185 | + ); |
| 186 | + |
| 187 | + throw new AuthenticationFailed('Authentication failed: invalid credentials.'); |
| 188 | + } |
| 189 | + |
| 190 | + $credentialsAttempted = true; |
| 191 | + |
| 192 | + $this->getSession()->sendMessageSync( |
| 193 | + new Message('Fetch.continueWithAuth', [ |
| 194 | + 'requestId' => $params['requestId'], |
| 195 | + 'authChallengeResponse' => [ |
| 196 | + 'response' => 'ProvideCredentials', |
| 197 | + 'username' => $username, |
| 198 | + 'password' => $password, |
| 199 | + ], |
| 200 | + ]) |
| 201 | + ); |
| 202 | + }); |
| 203 | + |
| 204 | + $this->getSession()->on('method:Fetch.requestPaused', function (array $params) { |
| 205 | + $this->getSession()->sendMessageSync( |
| 206 | + new Message('Fetch.continueRequest', [ |
| 207 | + 'requestId' => $params['requestId'], |
| 208 | + ]) |
| 209 | + ); |
| 210 | + }); |
| 211 | + |
| 212 | + $this->getSession()->sendMessageSync( |
| 213 | + new Message('Fetch.enable', [ |
| 214 | + 'handleAuthRequests' => true, |
| 215 | + 'patterns' => [ |
| 216 | + ['urlPattern' => '*'], |
| 217 | + ], |
| 218 | + ]) |
| 219 | + ); |
| 220 | + } |
| 221 | + |
163 | 222 | /** |
164 | 223 | * Sets the HTTP header necessary for basic authentication. |
165 | 224 | * |
|
0 commit comments