简体   繁体   中英

How do I authenticate with JWT using gRPC for PHP?

I've generated my client code from proto files. Now I'm trying to connect but get the 'jwt' is not located at the context error from server. Here's what I do:

$myServiceClient = new MyServiceClient(
    "$host:$port",
    [
        'credentials' => ChannelCredentials::createInsecure(),
        'update_metadata' => function ($metaData) use ($token) {
//            $metaData['authorization'] = ['jwt' . $token]; // doesn't work
//            $metaData['authorization']['jwt'] = $token; // doesn't work
//            $metaData['jwt'] = $token; // doesn't work
            $metaData['authorization'] = ['Bearer ' . $token]; // doesn't work

            return $metaData;
        },
    ]
);
$unaryCall = $myServiceClient->MyMethod(new MyMethodRequest());
$wait = $unaryCall->wait();

Try this

$myServiceClient = new MyServiceClient(
    "$host:$port",
    [
        'credentials' => ChannelCredentials::createInsecure(),
        'update_metadata' => function ($metaData) use ($token) {
            $metaData['Authorization'] = 'Bearer ' . $token; 
            return $metaData;
        },
    ]
);

Best HTTP Authorization header type for JWT

Or like this:

https://jwt.io/introduction

Authorization: Bearer <token>

The following works for me:

$myServiceClient = new MyServiceClient(
    "$host:$port",
    [
        'credentials' => ChannelCredentials::createInsecure(),
        'update_metadata' => function ($metaData) use ($token) {
            $metaData['jwt'] = [$token];

            return $metaData;
        },
    ]
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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