简体   繁体   English

PHP Slim 4 - 使用 Firebase JWT 令牌授权 api 请求

[英]PHP Slim 4 - Authorize api request using firebase JWT token

I'm trying to verify the idToken provided from firebase javascript sdk with the Tuupola Jwt middleware for slim 4 but I always get a 401 error.我正在尝试使用用于 slim 4 的 Tuupola Jwt 中间件验证从 firebase javascript sdk 提供的 idToken,但我总是收到 401 错误。 This is the client code I'm using to get the token:这是我用来获取令牌的客户端代码:

const provider = new firebase.auth.GoogleAuthProvider();
provider.addScope("profile");
provider.addScope("email");
firebase.auth().signInWithPopup(provider).then( (result) => {
 console.log(result);   
});

The auth flow will work correctly as expected and I'm able to pass the token into the Authorization header but I'm not able to verify it on the server where I'm using slim 4 for a Restful api.身份验证流程将按预期正常工作,并且我能够将令牌传递到 Authorization 标头中,但我无法在使用 slim 4 作为 Restful api 的服务器上对其进行验证。

I've read different question about this problem but none of this have helped me to solve this problem.我读过关于这个问题的不同问题,但这些都没有帮助我解决这个问题。

here is my middleware implementation:这是我的中间件实现:

use Tuupola\Middleware\CorsMiddleware;
use Tuupola\Middleware\JwtAuthentication;
use Slim\App as App;

return function(App $app) {
    $app->add(new Tuupola\Middleware\CorsMiddleware([
        "origin" => ["chrome-extension://oegddbimpfdpbojkmfibkebnagidflfc"],
        "methods" => ["GET", "POST", "OPTIONS"],
        "headers.allow" => ["Authorization"],
        "headers.expose" => [],
        "credentials" => true,
        "cache" => 86400
    ]));

//    $rawPublicKeys = file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com');
//    $keys = json_decode($rawPublicKeys, true);
    $keys = file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com');

    $app->add(new Tuupola\Middleware\JwtAuthentication([
        "algorithm" => ["RS256"],
        "header" => "X-Authorization",
        "regexp" => "/Bearer\s+(.*)$/i",
        "secret" => $keys,
        "secure" => false,
        "after" => function ($response, $arguments) {
            return $response->withHeader("X-Brawndo", "plants crave"); //this is only for test
        }
    ]));

};

and this is what I have inside my index.php file where slim app is running这就是我的 index.php 文件中的内容,其中运行了 slim 应用程序

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteCollectorProxy;
use Slim\Routing\RouteContext;
use Slim\Factory\AppFactory;
use Tuupola\Middleware\CorsMiddleware;

require_once __DIR__.'/vendor/autoload.php';

$app = AppFactory::create();

$authMiddleware = require_once __DIR__.'/middleware.php';
$authMiddleware($app);

$app->get('/keygen', function(Request $request, Response $response, $args){  
    $password = bin2hex(random_bytes(3));
    $response->getBody()->write( json_encode(['generated_password' => $password]) );
    return $response->withHeader('Content-Type','application/json');
});

$app->add(new Tuupola\Middleware\CorsMiddleware([
    "origin" => ["*"],
    "methods" => ["GET", "POST", "OPTIONS"],
    "headers.allow" => ["Authorization"],
    "headers.expose" => [],
    "credentials" => true,
    "cache" => 86400
]));

$app->run();

What I want to achive is to authenticate each request made from the client to the api using the firebase idToken provided after client login.我想要实现的是使用客户端登录后提供的 firebase idToken 对从客户端向 api 发出的每个请求进行身份验证。 When a request is made, the middleware will verify the token and then authorize the user or not to use the endpoint.当发出请求时,中间件将验证令牌,然后授权用户或不使用端点。

Is possible to fix this?有可能解决这个问题吗?

After a lot of debug I've found and solved the problem.经过大量调试后,我发现并解决了问题。 In my client code I was using the wrong idToken as Authorization: Bearer and also the header sended to the server was mismatching the middelware configuration, in my axios requests I was sending the X-Authorization header instead of Authorization .在我的客户端代码中,我使用了错误的idToken作为Authorization: Bearer并且发送到服务器的标头与中间件配置不匹配,在我的 axios 请求中,我发送的是X-Authorization标头而不是Authorization To get the correct token to use I've called firebase.auth().onAuthStateChanged( (user) =>{...}) method and when the user object become available I've called the getIdToken() method.为了使用正确的令牌,我调用了firebase.auth().onAuthStateChanged( (user) =>{...})方法,当用户对象可用时,我调用了getIdToken()方法。 This operation return the correct JWT token to use with the middleware to authenticate the requests.此操作返回正确的 JWT 令牌以与中间件一起使用以对请求进行身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM