Reputation: 12960
I'm making an authorization system in PHP
, and I came across this Bearer scheme of passing JWT tokens, I read [RFC 6750][1]. I've got the following doubts:
Authorization: Bearer fdbghfbfgbjhg_something
, how is server supposed to handle this, decodeFunc(explode(" ", $this->getRequest()->getHeader("Authorization"))[1])
?
[1]: https://www.rfc-editor.org/rfc/rfc6750Upvotes: 64
Views: 114244
Reputation: 3771
Improving the security because if token is not sent in the header that sent in URL, it will be logged by the network system, the server log.
Here is a good function to get Bearer tokens:
/**
* Get header Authorization
* */
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
Upvotes: 189
Reputation: 1607
The function searches for the header and removes the Bearer
prefix:
private function getBearerToken(): ?string
{
$headers = array_change_key_case(getallheaders(), CASE_LOWER);
if (!isset($headers['authorization'])) {
return null;
}
return trim(str_replace('Bearer', '', $headers['authorization']));
}
Upvotes: 1
Reputation: 1167
I would recommend to use the following RegEx to check, if it's a valid jwt-token:
/Bearer\s((.*)\.(.*)\.(.*))/
and access it also with matches[1].
This is the structure of a JWT-Token, see: https://jwt.io/
Upvotes: 3