Created
October 4, 2017 14:02
-
-
Save E1101/8b3b28331c8f9300a2fca81b44362dfe to your computer and use it in GitHub Desktop.
Parse Token From Request
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 | |
/** | |
* As per the Bearer spec (draft 8, section 2) - there are three ways for a client | |
* to specify the bearer token, in order of preference: Authorization Header, | |
* POST and GET. | |
* | |
* @param ServerRequestInterface $request | |
* | |
* @return null|string Token | |
*/ | |
function parseTokenStrFromRequest(ServerRequestInterface $request) | |
{ | |
# Get Token From Header: | |
if ($header = $request->getHeaderLine('Authorization')) { | |
if ( preg_match('/Bearer\s(\S+)/', $header, $matches) ) | |
return $token = $matches[1]; | |
} | |
# Get Token From POST: | |
if (strtolower($request->getMethod()) === 'post' | |
&& $contentType = $request->getHeaderLine('Content-Type') | |
) { | |
if ($contentType == 'application/x-www-form-urlencoded') { | |
// The content type for POST requests must be "application/x-www-form-urlencoded | |
$postData = $request->getParsedBody(); | |
foreach ($postData as $k => $v) { | |
if ($k !== 'access_token') continue; | |
return $token = $v; | |
} | |
} | |
} | |
# Get Token From GET: | |
$queryData = $request->getQueryParams(); | |
$token = (isset($queryData['access_token'])) ? $queryData['access_token'] : null; | |
return $token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment