简体   繁体   中英

“The token could not be parsed from the request” in jwt in laravel

I am facing "The token could not be parsed from the request" error in JWT in Laravel.

I have tried same code in localhost(Xampp in windows 7) it is working but on server it is not working.

I have passed "Authorization" token in header and also changed .htaccess file.

Please check below screenshot for passed token in request in angular 2.

在此处输入图片说明

Below is .htaccess file. (I have also tried this code in root .htaccess file and public .htaccess file both)

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1 [L]

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
</IfModule>

And I have used below code for authenticated token.

public function image_upload(Request $request){
    try{
        if($user = JWTAuth::parseToken()->authenticate()){
            \Api::success(['data' => $user]);
        }else{
            \Api::error("User is not found.");
        }
    }
    catch(\Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
        \Api::error(['type'=> 'expired','message' => 'Your login has been expired. Please login and try again.']);
        exit();
    }
    catch(\Tymon\JWTAuth\Exceptions\TokenInvalidException $e){
        \Api::error(['type'=> 'invalid','message' => $e->getMessage()]);
        exit();
    }
    catch(\Tymon\JWTAuth\Exceptions\JWTException $e){
        \Api::error(['type'=> 'invalid','message' => $e->getMessage()]);
        exit();
    }
}

Because of the problematic exclusion of the Authorization header by Apache, then if you need to save time you can pass the token into your requests, then in your controller, check if you have the token with:

public function image_upload(Request $request){
    return $request->token;
.....
}

Did you have any result? if you don't then you have to check if your request parameter has the token field. If you have the token in this controller, then you can still use the parseToken() method or simply (maybe for debugging purpose) use:

public function image_upload(Request $request){
    $user = JWTAuth::toUser($request->token));
    .......
}

I think this should be sufficient, the only mistake might be that you have applied a middleware that is causing this issue to the route you are accessing.

PS: I tried this on Laravel 5.2*

I hope this helps.

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