How to Properly Use Bearer Tokens

How to properly use Bearer tokens?

1.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 ....

2.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;
}

PHP Angular - JWT Authorization Bearer Token

Hi im speak spanish but i'm the same situation and I gonna tell u which way i took

searching for google and here I found u have to receive the JWT in $_SERVER['HTTP_AUTHORIZATION'] but this doesn't work at least in my shared host, I tried play whit the .htaccess file but nothing, you can check the details here [Apache 2.4 + PHP-FPM and Authorization headers also u can send the JWT through angular in JSON format to your php file, but i would recommend you to use HttpClientModule instead of HttpRequest if you want to send your data via GET or POST,

In PHP, this my test file, I sent the JWT in the URL this is not the best form to performance the tokens but in my case works, I hope it helps.

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require_once 'jwt/src/BeforeValidException.php';
require_once 'jwt/src/ExpiredException.php';
require_once 'jwt/src/SignatureInvalidException.php';
require_once 'jwt/src/JWT.php';
use \Firebase\JWT\JWT;

$llave = 'TULLAVESECRETA';

$authHeader = $_GET['tok'];

try{
$decoded = JWT::decode($authHeader, $llave, array('HS256'));
echo json_encode($decoded);
}
catch(Exception $e){
http_response_code(200);
echo json_encode(array(
"mensaje" => "Vuelve a iniciar sesion.",
"error" => $e->getMessage()
));
}

?>

I will edit if you comment

When to validate JWT

Typically, JWT tokens are validated when are sent from the client-side to the server-side. As these tokens are signed, if anyone tries to tamper with the token before sending it to the server-side endpoint, the token verification will fail, therefore these tokens are a secure way of sending the session of an authenticated user to an API or a server endpoint.

These JWTs can be also transferred between servers or different application layers, and it always would be a good practice to verify the token before processing it. It is adding a layer of security to avoid anyone sending tokens to that layer directly and skipping the validation.

What is the OAuth 2.0 Bearer Token exactly?

Bearer Token

A security token with the property that any party in possession of
the token (a "bearer") can use the token in any way that any other
party in possession of it can. Using a bearer token does not
require a bearer to prove possession of cryptographic key material
(proof-of-possession).

The Bearer Token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for you a Token. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer token basically says "Give the bearer of this token access".

The Bearer Token is normally some kind of opaque value created by the authentication server. It isn't random; it is created based upon the user giving you access and the client your application getting access.

In order to access an API for example you need to use an Access Token. Access tokens are short lived (around an hour). You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for. Example: I can't just take a bearer token created for your application and use it with my application it wont work because it wasn't generated for me.

Google Refresh token looks something like this: 1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM

copied from comment: I don't think there are any restrictions on the bearer tokens you supply. Only thing I can think of is that its nice to allow more than one. For example a user can authenticate the application up to 30 times and the old bearer tokens will still work. oh and if one hasn't been used for say 6 months I would remove it from your system. It's your authentication server that will have to generate them and validate them so how it's formatted is up to you.

Update:

A Bearer Token is set in the Authorization header of every Inline Action HTTP Request. For example:

POST /rsvp?eventId=123 HTTP/1.1
Host: events-organizer.com
Authorization: Bearer AbCdEf123456
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)

rsvpStatus=YES

The string "AbCdEf123456" in the example above is the bearer authorization token. This is a cryptographic token produced by the authentication server. All bearer tokens sent with actions have the issue field, with the audience field specifying the sender domain as a URL of the form https://. For example, if the email is from noreply@example.com, the audience is https://example.com.

If using bearer tokens, verify that the request is coming from the authentication server and is intended for the the sender domain. If the token doesn't verify, the service should respond to the request with an HTTP response code 401 (Unauthorized).

Bearer Tokens are part of the OAuth V2 standard and widely adopted by many APIs.



Related Topics



Leave a reply



Submit