- composer 安装包
composer require tymon/jwt-auth
- config/app.php 注册服务提供者
'providers' => [
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
]
- 发布生成配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
执行后 会在config 下自动生成 jwt.php 文件
- 生成 JWT_SECRE
php artisan jwt:secret
执行后会在.env 中自动生成:
JWT_SECRET=IVYIoZuMhB2vUE6HQQOinyYhSL2DMhuVxsRNVAqkEzO3W3Qe9nG3G5SIH6GQG1Bd
- config/auth.php 中配置 guards
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'user',
],
],
'providers' => [
//这里的users就是上面api中的provider的值users
'user' => [
'driver' => 'eloquent',
'model' => App\Models\Api\User::class,
//注意这里的路径,我的api在Api目录下
],
],
- 新建 App\Models\Api\User 模型类
注意要继承 Authenticatable 并且 是JWTSubject 接口的实现
<?php
namespace App\Models\Api;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* 关联到模型的数据表
*
* @var string
*/
protected $table = 'user';
/**
* 表明模型是否应该被打上时间戳
*
* @var bool
*/
public $timestamps = true;
const CREATED_AT = 'createtime';
const UPDATED_AT = null;//不需要updatetime 可以设为null即可关闭
/**
* 模型日期列的存储格式默认是Y-m-d H:i:s,使用U改为时间戳
*
* @var string
*/
//protected $dateFormat = 'U';
/**
* 可以被批量赋值的属性.
*
* @var array
*/
protected $fillable = ['username','phone','part_id','group','account','password','salt'];
/**
* 在数组中隐藏的属性
*
* @var array
*/
protected $hidden = ['password','salt'];
//格式化输出时间
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
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 [];
}
}
- 注册路由
JWT 认证扩展包附带了允许我们使用的中间件。在 app/Http/Kernel.php 中注册 auth.jwt 中间件
protected $routeMiddleware = [
....
'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
];
- 创建api路由
Route::post('login', 'ApiController@login');
Route::post('register', 'ApiController@register');
Route::group(['middleware' => 'auth.jwt'], function () {
Route::get('user', 'ApiController@user');
Route::get('logout', 'ApiController@logout');
Route::get('refresh', 'ApiController@refresh');
});
- 控制器使用
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\RegisterAuthRequest;
use App\Models\Api\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use JWTAuth;
use Illuminate\Support\Str;
class ApiController extends Controller
{
public $loginAfterSignUp = true;
public function register(RegisterAuthRequest $request)
{
$data=$request->all();
$data['salt']=Str::random(4);
$data['password']=md5($data['password'].$data['salt']);
User::create($data);
/*if ($this->loginAfterSignUp) {
return $this->login($request);
}*/
return response()->json([
'success' => true,
'data' => []
], 200);
}
public function login(Request $request)
{
$input = $request->only('account', 'password');
//此处可以自己查数据库,判断是否用户名和密码正确
$user = User::query()->where(['account' => $input['account']])->firstOrFail();
//生成token两种方式
//$token = Auth::guard('api')->fromUser($user);
$token = JWTAuth::fromUser($user);
//dd($token);die;
return response()->json([
'success' => true,
'token' => $token,
'user' => $user,
]);
}
public function logout(Request $request)
{
Auth::guard('api')->invalidate();
return response()->json([
'success' => true,
'msg' => "退出成功"
]);
}
public function refresh(Request $request)
{
$newtoken=Auth::guard('api')->refresh();
return response()->json([
'success' => true,
'msg' => "token已刷新",
"token"=>$newtoken
]);
}
public function user(Request $request)
{
//两种方式都行
$user = Auth::guard('api')->user();
//$user = JWTAuth::authenticate();
return response()->json([
'success' => true,
'user' => $user,
]);
}
}
- 测试