簡體   English   中英

PHP Angular - JWT 授權承載令牌

[英]PHP Angular - JWT Authorization Bearer Token

我正在嘗試獲取 angular 向 php 發送的授權令牌。 我的 angular 攔截器看起來如下

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());
    }
}

我在控制台記錄了查看 output 的請求,它有令牌。 在此處輸入圖像描述

然后我轉到開發人員工具的網絡選項卡以查看令牌是否在請求中並且它在那里。 在此處輸入圖像描述

現在如何獲取 php 中的令牌? 我試着按照這個問題的答案。 但這也無濟於事。 以下是使用上述答案中的代碼時的 output。

在此處輸入圖像描述

嗨,我說西班牙語,但我也有同樣的情況,我會告訴你我采取了哪種方式

搜索谷歌,在這里我發現你必須在 $_SERVER['HTTP_AUTHORIZATION'] 中接收 JWT 但這至少在我的共享主機中不起作用,我嘗試播放 .htaccess 文件,但沒有,你可以在這里查看詳細信息[ 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,

在 PHP 中,這是我的測試文件,我在 URL 中發送了 JWT 這不是執行令牌的最佳形式,但在我的情況下,我希望它有所幫助。

<?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()
    ));
}

?>

如果您發表評論,我將編輯

在位於 api 文件夾的 .htaccess 文件中包含以下行:

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

完整答案在這里: PHP POST 請求中缺少授權 header

然后您可以使用$_SERVER['HTTP_AUTHORIZATION']

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

您仍然需要從$token中刪除“Bearer”文本。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM