当前位置:网站首页>Laravel8 uses passport authentication to log in and generate a token
Laravel8 uses passport authentication to log in and generate a token
2022-07-06 23:24:00 【Elante pace】
install passport
composer require laravel/passport
Execute the migration command
php artisan migrate
Create encryption keys required to generate security access tokens
php artisan passport:install
App\Models\ApiUser lead 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
Let go of 'App\Models\Model' => 'App\Policies\ModelPolicy' Notes
boot Next 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 The period of validity of the certification Passport::tokensExpireIn(now()->addHour(2)); // Refresh token The period of validity of the certification Passport::refreshTokensExpireIn(now()->addDays(30)); Passport::personalAccessTokensExpireIn(now()->addMonths(6));}
}
stay config/auth.php Middle configuration
'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'=>' Account number or password cannot be empty ','data'=>[]]);
}
// Verify account and password
$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'=>' The number of requests on that day has reached the maximum ','data'=>[]]);
}
$token = $user->createToken('api')->accessToken;
$user->increment('click');
$data = [
'expire'=>3600*24*30,
'token'=>$token
];
return response()->json(['code'=>400,'msg'=>' Generate token success ','data'=>$data]);
}else{
return response()->json(['code'=>403,'msg'=>' Incorrect account or password ','data'=>[]]);
}
}边栏推荐
- DR-Net: dual-rotation network with feature map enhancement for medical image segmentation
- 服务器的系统怎么选者
- Gpt-3 is a peer review online when it has been submitted for its own research
- #DAYU200体验官# 首页aito视频&Canvas绘制仪表盘(ets)
- 请问oracle-cdc用JsonDebeziumDeserializationSchema反序列化
- MySQL数据库之JDBC编程
- Les entreprises ne veulent pas remplacer un système vieux de dix ans
- 「小程序容器技术」,是噱头还是新风口?
- Motion capture for snake motion analysis and snake robot development
- Spark Tuning (II): UDF reduces joins and judgments
猜你喜欢

AI表现越差,获得奖金越高?纽约大学博士拿出百万重金,悬赏让大模型表现差劲的任务...

Today's sleep quality record 78 points

Modules that can be used by both the electron main process and the rendering process

Motion capture for snake motion analysis and snake robot development

Cover fake big empty talk in robot material sorting

MySQL数据库之JDBC编程

How to choose indoor LED display? These five considerations must be taken into account

None of the strongest kings in the monitoring industry!
docker启动mysql及-eMYSQL_ROOT_PASSWORD=my-secret-pw问题解决

不要再说微服务可以解决一切问题了
随机推荐
#DAYU200体验官# 在DAYU200运行基于ArkUI-eTS的智能晾晒系统页面
docker中mysql开启日志的实现步骤
JS addition, deletion, modification and query of JSON array
【Unity】升级版·Excel数据解析,自动创建对应C#类,自动创建ScriptableObject生成类,自动序列化Asset文件
Method of canceling automatic watermarking of uploaded pictures by CSDN
[launched in the whole network] redis series 3: high availability of master-slave architecture
企業不想換掉用了十年的老系統
AcWing 4300. Two operations (minimum number of BFS searches)
每日刷题记录 (十五)
On file uploading of network security
koa2对Json数组增删改查
flinksql select id ,count(*) from a group by id .
Example code of MySQL split string as query condition
前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
Unified Focal loss: Generalising Dice and cross entropy-based losses to handle class imbalanced medi
Pdf batch splitting, merging, bookmark extraction, bookmark writing gadget
Case recommendation: An Qing works with partners to ensure that the "smart court" is more efficient
浅谈网络安全之文件上传
Realize colorful lines and shape your heart
GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议