Created
September 9, 2021 17:50
-
-
Save hbackman/06216c5b0704248a15d24cf65fcf68dc to your computer and use it in GitHub Desktop.
PSR Compliant Basic Auth Decode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the HTTP Basic Auth information from the request. | |
* | |
* @param ServerRequestInterface $request | |
* | |
* @return array | |
*/ | |
function getBasicAuth(ServerRequestInterface $request): array | |
{ | |
$header = $request->getHeader('authorization'); | |
$header = reset($header); | |
preg_match("/^Basic (.*)$/", $header, $matches); | |
if (count($matches) <= 1) { | |
return [ | |
'username' => null, | |
'password' => null | |
]; | |
} | |
$token = $matches[1]; | |
$token = base64_decode($token); | |
[ $username, | |
$password ] = explode(':', $token); | |
return compact('username', 'password'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment