我坚持了3天左右。基本上,我试图使用Tymon在laravel中生成JWT令牌。这是我的控制器文件。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use JWTAuth;
use JWT;
use Tymon\JWTAuthExceptions\JWTException;
use Tymon\JWTAuth\Contracts\JWTSubject as JWTSubject;
class AuthenticateController extends Controller
{
public function index()
{
//
}
public function authenticate(Request $request)
{
$user = User::where('email', $request->only('email'))->first();
dd($user); //This does show some output
$token = JWTAuth::fromUser($user); //returns error message
return ["error" => NULL, "token" => $token];
}
}
我使用Chrome邮递员测试了这个API,但它报告了此错误:
JWT.php第73行中的ErrorException: 传递给Tymon \ JWTAuth \ JWT :: fromUser()的参数1必须是Tymon \ JWTAuth \ Contracts \ JWTSubject的实例,App / User实例给出,在/ Users / shankerm / mccadmin / laravel / vendor / laravel / framework中调用第217行的/src/Illuminate/Support/Facades/Facade.php并定义了
请给我一些建议。我是Laravel的新手并且长期以来一直在努力奋斗。感谢。
答案 0 :(得分:3)
您使用的是较新版本的软件包。这要求User Model
实现此合同。通过在模型中执行此操作来解决此问题:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements JWTSubject {
答案 1 :(得分:0)
首先,您需要在User模型上实现Tymon \ JWTAuth \ Contracts \ JWTSubject合同,这需要您实现getJWTIdentifier()和getJWTCustomClaims()这两种方法。
下面是示例代码外观。请根据自己的需要进行必要的更改。
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
Configure Auth guard
Note: This will only work if you are using Laravel 5.2 and above.
Inside the config/auth.php file you will need to make a few changes to configure Laravel to use the jwt guard to power your application authentication.
Make the following changes to the file:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
...
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Here we are telling the api guard to use the jwt driver, and we are setting the api guard as the default.
答案 2 :(得分:0)
根据以前的经验可能会发生两个问题
将jwt设置为默认身份验证驱动程序。您可以这样做
'api'=> [ '驱动程序'=>'jwt', '提供者'=>'用户', 'hash'=>否, ]
class用户扩展了Authenticatable实现JWTSubject { 然后通过以下界面实现功能
/ ** * @inheritDoc * / 公共函数getJWTIdentifier() { 返回$ this-> getKey(); }
/**
* @inheritDoc
*/
public function getJWTCustomClaims()
{
return [];
}
也可能是您尚未生成jwt身份验证密钥
php artisan jwt:secret
与此相关,您应该在.env
中有一个这样的条目JWT_SECRET={value generated}
答案 3 :(得分:0)
除了 JWT Documentation 中提供的步骤之外,请评论 config/auth.php 中的以下可用部分,该部分在安装 Laravel 后默认提供。
'users' => ['driver' => 'database', 'table' => 'users',],