我有一个使用Tymon \ JWTAuth来验证用户身份的Larvel API。
工作正常。
由于某些原因,我在web.php
中也有一条无人看守的路线:
Route::get('myroute', 'MyController@mymethod');
MyController @ mymethod的代码如下:
$user = JWTAuth::toUser($request->input('token'));
// I tried also this:
// JWTAuth::setToken($request->input('token'));
// $user = JWTAuth::authenticate();
我在浏览器中使用此网址调用路线:/myroute?token=eyJ0eXAiOiJKV1QiLCJhbGci....
问题是我在JWT.php中有一个例外:
Tymon \ JWTAuth \ Exceptions \ JWTException 需要令牌
JWT.php
protected function requireToken()
{
if (! $this->token) {
throw new JWTException('A token is required');
}
}
如何解码作为URL参数传递但不在请求标题中的令牌?
答案 0 :(得分:1)
我使用此代码解决了它:
use Namshi\JOSE\SimpleJWS;
$secret = config('jwt.secret');
$jws = SimpleJWS::load($token);
if (!$jws->isValid($secret)) {
return response()->json([], 401); // unauthorized
}
$payload = $jws->getPayload();
但我宁愿直接使用JWTAuth
答案 1 :(得分:1)
代替
$ user = JWTAuth :: toUser($ request-> input('token'));
使用
$ user = $ this-> jwt-> User();
答案 2 :(得分:0)
如果您使用的是jwt-auth dev,则旧版本中的toUser方法将删除上述错误,请尝试以下操作:
// Get the currently authenticated user
$user = auth()->user();
如果未对用户进行身份验证,则将返回null。