我在 Laravel 的 JWT 中遇到“无法从请求中解析 token ”错误。
我在本地主机(Windows 7 中的 Xampp)中尝试过相同的代码,它可以正常工作,但在服务器上却无法正常工作。
我已经在 header 中传递了"Authorization" token 并且还更改了.htaccess 文件。
请检查下面的屏幕截图以获取 Angular 2 中请求中传递的 token 。
下面是.htaccess 文件。 (我还在根 .htaccess 文件和公共(public) .htaccess 文件中都尝试过这段代码)
<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>
我已经使用下面的代码来验证 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();
}
}
最佳答案
由于 Apache 对 Authorization
header 的排除存在问题,如果您需要节省时间,您可以将 token 传递到您的请求中,然后在您的 Controller 中,检查您是否拥有 token :
public function image_upload(Request $request){
return $request->token;
.....
}
有结果了吗?如果你不这样做,那么你必须检查你的请求参数是否有 token
字段。如果您在此 Controller 中拥有 token ,那么您仍然可以使用 parseToken()
方法或简单地(可能出于调试目的)使用:
public function image_upload(Request $request){
$user = JWTAuth::toUser($request->token));
.......
}
我认为这应该足够了,唯一的错误可能是您将导致此问题的 middleware
应用于您正在访问的路由。
PS: I tried this on Laravel 5.2*
希望对您有所帮助。
关于php - laravel 中的 jwt 中的 "The token could not be parsed from the request",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42363316/