Skip to content

Instantly share code, notes, and snippets.

@E1101
Created October 4, 2017 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save E1101/8b3b28331c8f9300a2fca81b44362dfe to your computer and use it in GitHub Desktop.
Save E1101/8b3b28331c8f9300a2fca81b44362dfe to your computer and use it in GitHub Desktop.
Parse Token From Request
<?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