1

I am trying to get the authorization token being sent by angular to php. My angular intercepter looks as follows

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (localStorage.getItem('token') != null) {
        const clonedReq = req.clone({
            headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
        });
        return next.handle(clonedReq).pipe(
            tap(
                succ => { },
                err => {
                    if (err.status == 401){
                        localStorage.removeItem('token');
                        localStorage.removeItem('username');
                        this.router.navigateByUrl('/user/login');
                    }
                }
            )
        )
    }
    else {
        return next.handle(req.clone());
    }
}

I console logged the request to see the output and it has the token. enter image description here

Then i went to Network tab of developer tools to see if token was in the request and it was there. enter image description here

Now how do I get the token in php? I tried following the answer to this question. But that doesn't help either. Following is the output when using the code in above answer.

enter image description here

Saad Bashir
  • 4,341
  • 8
  • 30
  • 60

2 Answers2

1

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

0

Include the following lines in the .htaccess file located on the api's folder:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Full answer here: Authorization header missing in PHP POST request

Then you can read your "Bearer "+token with $_SERVER['HTTP_AUTHORIZATION'] or

$requestHeaders = apache_request_headers();
$token = $requestHeaders["Authorization"]; 

You will still need to strip the "Bearer " text from $token.

if (preg_match('/Bearer\s(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
// alternately '/Bearer\s((.*)\.(.*)\.(.*))/' to separate each JWT string
    $stripped_token =  $matches[1];
}