Jwt authorization header "wrong number of segment"

I am working with jwt authorization. I want to handle the wrong number of segment error.

public function token()
{
if ($this->request->is(‘post’)) {
$user = $this->Auth->identify();
$this->set([
‘success’ => true,
‘user’ => $user,
‘data’ => [
‘token’ => $token = \Firebase\JWT\JWT::encode([
‘id’ => $user[‘id’],
‘exp’ => time() + 604800,
],
Security::salt()),
],
‘_serialize’ => [‘success’, ‘data’ ,‘user’],
]);
}
else {
throw new UnauthorizedException(“Invalid email or password, try again”);
}

    }

https://localhost/cakephp/forms.json
Method : POST
Content-Type:application/json
Authorization:Bearer df41564621212

{
“message”: “Wrong number of segments”,
“url”: “/forms.json”,
“code”: 500,
“file”: “E:\xampp\htdocs\cakephp\vidhya-venkatesan\vendor\firebase\php-jwt\src\JWT.php”,
“line”: 78
}

I want to handle the error when token is incorrect. Can someone help please.

Hi,

The header Authorization looks weird, normally the token is longer. You can easily check if the token received is correct on this website and your security key :wink:.

And if it can help you, here is how I did (cake 3.6.x):

    public function token()
{
    $user = $this->Auth->identify(); 
    $expire = 120000; // time() + 300;
    
    if (!$user) {
        $this->response->withStatus(401);            
        throw new UnauthorizedException('Invalid username or password');
    } else {   
        Log::write('info', $this->request->clientIp() . ' get token api key',['scope'=>['api-access']]);
        $this->response->getBody()->write(json_encode([
            'success' => true,
            'user' => [
                'uid'      => $user['id'],
                'username' => $user['username'],
            ],
            'auth' => [
                'expiresIn' => $expire,
                'token' => JWT::encode([
                    'iss' => 'testAuthor',
                    'sub' => $user['id'],
                    'exp' => $expire 
                ], Security::salt(Configure::read('Security.salt')))
            ],              
        ]));                                    
    }     
    
    return $this->response; 
}