jwt auth laravel 5 给出错误无法从请求中解析令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33914727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:44:22  来源:igfitidea点击:

jwt auth laravel 5 gives error The token could not be parsed from the request

angularjslaravelauthenticationjwtjson-web-token

提问by Stacy J

I've set up a frontend angular system and backend laravel system. Everything is working well but the tokens aren't being generated in login process. The registration process works well and stores the users details in the database.

我已经建立了一个前端角度系统和后端 Laravel 系统。一切正常,但在登录过程中没有生成令牌。注册过程运行良好,并将用户详细信息存储在数据库中。

Routes.php

路由.php

Route::post('/api/register', 'RegisterController@register');
Route::post('api/authenticate', 'LoginController@authenticate');
Route::get('api/authenticate/user/email/{email}/password/{password}', 'LoginController@getAuthenticatedUser');

RegisterController.php

注册控制器.php

 public function register(Request $request){
    $newuser= $request->all();
    $password=Hash::make($request->input('password'));

    $newuser['password'] = $password;
    return Register::create($newuser);
}

LoginController.php

登录控制器.php

/*public function authenticate(Request $request){*/
public function authenticate($email, $password){
    /*$credentials = $request->only('email', 'password');*/
    $credentials = array('email' => $email, 'password' => $password);
    try{
        if(! $token = JWTAuth::attempt($credentials)){
            return \Response::json(['error' => 'invalid_credentials'], 401);
        }
    }
    catch(JWTException $e){
        return \Response::json(['error' => 'could_not_create_token'], 500);
    }
    return \Response::json(compact('token'));
}


public function getAuthenticatedUser($email, $password){
    try{
        if(! $user = JWTAuth::parseToken()->authenticate($email, $password)){
            return \Response::json(['user_not_found'], 404);
        }
    }
    catch(Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
        return \Response::json(['token_expired'], $e->getStatusCode());
    }
    catch(Tymon\JWTAuth\Exceptions\TokenInvalidException $e){
        return \Response::json(['token_invalid'], $e->getStatusCode());
    }
    catch(Tymon\JWTAuth\Exceptions\JWTException $e){
        return \Response::json(['token_absent'], $e->getStatusCode());
    }
    return \Response::json(compact('user'));
    /*return \Response::json(array('user' => 'Steve', 'state' => 'CA'));*/
}

authController.js

验证控制器.js

reglogApp.controller('AuthController', function($scope, $http, $auth, $rootScope, $state){
$scope.email='';
$scope.password='';
$scope.newUser={};
$scope.loginError=false;
$scope.loginErrorText='';


$scope.login = function(){
    var credentials = {
        email: $scope.email,
        password: $scope.password
    }
    console.log('Entered Login Function', credentials);

    $auth.login(credentials).then(function(){
        return $http.get('http://reglog.xyz.com/api/authenticate/user/email/[email protected]/password/ABHVF123456789000');

        },function(error){
            $scope.loginError = true;
            $scope.loginErrorText = error.data.error;
            console.log('Login Error', $scope.loginErrorText);
        }).then(function(response){
                $rootScope.currentUser = response.data.user;
                $scope.loginError = false;
                $scope.loginErrorText = '';
                console.log('Current User', $rootScope.currentUser);
                $state.go('dashboard');
        });

}

$scope.register = function(){
    $scope.name = $scope.newUser.name;
    $scope.email = $scope.newUser.email;
    $scope.password = $scope.newUser.password;
    console.log($scope.name, $scope.email, $scope.password);
    $http.post('http://reglog.xyz.com/api/register', $scope.newUser).success(function(data){
        console.log('Registered');
        $scope.email = $scope.newUser.email;
        $scope.password = $scope.newUser.password;
        $scope.login();
    });
}

});

});

回答by Vedansh Agrawal

You need to send authorization token in the header. You might need to modify your Apache settings to allow for authorization headers to be sent.

您需要在标头中发送授权令牌。您可能需要修改 Apache 设置以允许发送授权标头。

Authorization: Bearer {yourtokenhere}

授权:持有人 {yourtokenhere}

You can modify your .htaccess file with:

你可以修改你的 .htaccess 文件:

RewriteCond %{HTTP:Authorization} ^(.*)

RewriteCond %{HTTP:Authorization} ^(.*)

RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

重写规则 .* - [e=HTTP_AUTHORIZATION:%1]

回答by Vladislav Rastrusny

JWTAuth::parseToken()requires token to be sent in the header in the following format:

JWTAuth::parseToken()要求以以下格式在标头中发送令牌:

Authorization: Bearer {yourtokenhere}

And I believe, you don't do that. So, your getAuthenticatedUserfails.

我相信,你不会那样做。所以,你的getAuthenticatedUser失败。

回答by Dhanesh Narvekar

You might try to set always_populate_raw_post_data = -1 in php.ini

您可以尝试在 php.ini 中设置 always_populate_raw_post_data = -1

This worked for me

这对我有用

回答by John Huang

I guess the LoginController::getAuthenticatedUser()seems like to authenticate a user's credentials (email and password).

我猜这LoginController::getAuthenticatedUser()似乎是为了验证用户的凭据(电子邮件和密码)。

However, there is also JWTAuth::parseToken()->authenticate($email, $password)in the getAuthenticatedUser()method. The JWTAuth::parseToken()is responsible for validating the token from request 1. The client MUST send a request to the GET /api/authenticateendpoint with the token.

然而,也有JWTAuth::parseToken()->authenticate($email, $password)getAuthenticatedUser()法。该JWTAuth::parseToken()负责从请求验证令牌1。客户端必须使用令牌向GET /api/authenticate端点发送请求。

In my opinion, the LoginController::authenticate()identifies and responses user's information to client by JSON Web Token. The emailand passwordparameters are NOT necessary in LoginController:: getAuthenticatedUser(), because the token is able to identify a user.

在我看来,LoginController::authenticate()JSON Web Token 识别和响应用户的信息给客户端。中的emailpassword参数不是必需的LoginController:: getAuthenticatedUser(),因为令牌能够识别用户。

LoginController.php

登录控制器.php

public function getAuthenticatedUser(){
    try{
        if(! $user = JWTAuth::parseToken()->authenticate()){
            return \Response::json(['user_not_found'], 404);
        }
    }
    catch(Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
        return \Response::json(['token_expired'], $e->getStatusCode());
    }
    catch(Tymon\JWTAuth\Exceptions\TokenInvalidException $e){
        return \Response::json(['token_invalid'], $e->getStatusCode());
    }
    catch(Tymon\JWTAuth\Exceptions\JWTException $e){
        return \Response::json(['token_absent'], $e->getStatusCode());
    }
    return \Response::json(compact('user'));
    /*return \Response::json(array('user' => 'Steve', 'state' => 'CA'));*/
}

回答by Sathish

Simple edit .htaccess file. i.e., inside /public/.htaccess

简单编辑 .htaccess 文件。即,在 /public/.htaccess 里面



Options -MultiViews

选项 - 多视图

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ / [L,R=301]
# Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]