安装passport
composer require laravel/passport
执行迁移命令
php artisan migrate?
创建生成安全访问令牌所需的加密键
php artisan passport:install
App\Models\ApiUser 引 Trait
<?php ? ?? namespace App\Models; ? ?? use Laravel\Passport\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as AuthUser; ? ?? class ApiUser extends AuthUser { ? ? use HasApiTokens, Notifiable; }???
App\Providers\AuthServiceProvider
放开? 'App\Models\Model' => 'App\Policies\ModelPolicy' 的注释
boot下?Passport::routes();
<?php ? ?? namespace App\Providers; ? ?? use Laravel\Passport\Passport; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; ? ?? class AuthServiceProvider extends ServiceProvider { ? ? /** ? ? ?* The policy mappings for the application. ? ? ?* ? ? ?* @var array ? ? ?*/ ? ? protected $policies = [ ? ? ? ? 'App\Models\Model' => 'App\Policies\ModelPolicy', ? ? ]; ? ?? ? ? /** ? ? ?* Register any authentication / authorization services. ? ? ?* ? ? ?* @return void ? ? ?*/ ? ? public function boot() ? ? { ? ? ? ? $this->registerPolicies(); ? ?? ? ? ? ? Passport::routes();
????//token认证有效期????
????Passport::tokensExpireIn(now()->addHour(2));
????//刷新token认证有效期
????Passport::refreshTokensExpireIn(now()->addDays(30));
????Passport::personalAccessTokensExpireIn(now()->addMonths(6));
? ? } }?
在config/auth.php中配置
'guards' => [ ? ? 'web' => [ ? ? ? ? 'driver' => 'session', ? ? ? ? 'provider' => 'users', ? ? ],
????'apiweb'=>[
????????'driver' => 'session', ? ? ? ? 'provider' => 'apiusers',
?????],
? ? 'api' => [ ? ? ? ? 'driver' => 'passport', ? ? ? ? 'provider' => 'apiusers', ? ? ? ? // 'hash' => false, ? ? ], ],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'apiusers' => [
'driver' => 'eloquent',
'model' => \App\Models\ApiUser::class,
],
]
?App\Http\Controllers\Api\LoginController
public function login(Request $request)
{
try {
$this->validate($request,[
'username'=>'required',
'password'=>'required'
]);
} catch (\Exception $e){
return response()->json(['code'=>403,'msg'=>'账号或密码不能为空','data'=>[]]);
}
????// 验证账号和密码
$bool = auth()->guard('apiweb')->attempt($request->except('/api/login'));
if($bool)
{
$user = auth()->guard('apiweb')->user();
if($user->click > env('APINUM'))
{
return response()->json(['code'=>405,'msg'=>'当日请求次数已达上限','data'=>[]]);
}
$token = $user->createToken('api')->accessToken;
$user->increment('click');
$data = [
'expire'=>3600*24*30,
'token'=>$token
];
return response()->json(['code'=>400,'msg'=>'生成token成功','data'=>$data]);
}else{
return response()->json(['code'=>403,'msg'=>'账号或密码不正确','data'=>[]]);
}
}
|