我在Laravel中构建了一个api,使用tymondesign/jwt-auth对用户进行身份验证。
我遵循了github上的教程,登录工作正常:
public function login() {
if (!$token = JWTAuth::attempt(Input::only('email', 'password'))) {
return response()->json(['error' => true], HttpResponse::HTTP_UNAUTHORIZED);
}
$user = User::where('email', Input::get('email'))->first();
return response()->json(array(
'user' => $user,
'token' => compact('token')['token'])
);
}对于响应,我得到了令牌。
但每次我尝试使用我得到的toke时:
[
"Token is invalid"
]即:
public function getUser() {
$token = JWTAuth::getToken();
return response()->json(JWTAuth::toUser($token));
}这是一个带有标头Authorization: Bearer {{token}}的GET to {{url}}/api/getUser
我的routes.php包含以下内容:
Route::group(array('prefix' => 'api'), function() {
Route::post('/login', 'API\UserController@login');
Route::get('/getUser', ['before' => 'jwt-auth', 'uses' => 'API\UserController@getUser']);
});我怎样才能让这个令牌工作呢?我是不是漏掉了什么?
更新:
我得到了一个像这样的令牌:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL3NtYXJ0YXBwXC9hcGlcL2xvZ2luIiwiaWF0IjoxNDY2Mjc5ODUxLCJleHAiOjE0NjYyODM0NTEsIm5iZiI6MTQ2NjI3OTg1MSwianRpIjoiYjNkZjViZGNiMjQ2YWU0NzVlZDYwODQxMWFlZDNkMTAifQ.pqU0pWKVzmOel51ObyE9vKLk07tefh2lDE-fp-AOavE在https://jwt.io上检查令牌后,我得到了无效的签名。为什么我得到了无效的签名,我怎样才能使它有效?
发布于 2016-06-18 22:21:57
尝尝这个
public function getUser() {
// set the token on the object
JWTAuth::parseToken();
// get the user from token
$user = JWTAuth::parseToken()->authenticate();
return response()->json(compact('user'));
}发布于 2016-07-06 12:57:20
尝尝这个,
定义一个构造函数,这样你就可以通过使用$this-> JWTAuth ->toUser()来获取用户,而不需要在函数中重复使用JWTAuth $jwtauth。
private $jwtauth;
public function __construct(JWTAuth $jwtauth)
{
$this->jwtauth = $jwtauth;
}
public function getUser()
{
$user = $this->jwtauth->toUser();
return response($user);
}发布于 2020-05-14 08:00:39
你可以像这样做:
public function login() {
if (!$token = JWTAuth::attempt(Input::only('email', 'password'))) {
return response()->json(['error' => true],
HttpResponse::HTTP_UNAUTHORIZED);
}
$user = User::where('email', Input::get('email'))->first();
return response()->json(array(
'user' => $user,
'token' => compact(['token'])
);
}https://stackoverflow.com/questions/37897449
复制相似问题