当前位置:网站首页>Laravel8- use JWT
Laravel8- use JWT
2022-04-23 03:03:00 【Stupid little attendant】
laravel8- Use jwt
jwt- Official website
https://jwt-auth.readthedocs.io/en/develop/laravel-installation
install
- First step :composer Pull the latest version
composer require tymon/jwt-auth
- The second step : Add service provider (Laravel 5.4 Or below )
Add the service provider to the configuration file config/app.php Medium providers Array , As shown below :
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
'aliases' => [
...
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],
- The third step : Run the following command to publish the package configuration file
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
After running, there should be a config/jwt.php file , Allows you to configure the basics of this package
- Step four : Run the following command to generate a key
php artisan jwt:secret
After operation .env The file will generate a JWT_SECRET
stay laravel Configuration in the project
- First step : To configure config/auth.php
stay config/auth.php in , take api Of driver Change to drive jwt
Then register and write it yourself model
- The second step : Define routes
Specific code
- controller - newly build AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
/** * Create a new AuthController instance. * * @return void */
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */
public function login(Request $request)
{
$credentials = $request->only('name', 'password');
if (count($credentials) < 2) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = User::where('name', $credentials['name'])
->where('password', ($credentials['password']))
->first();
if (empty($user) || !$token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */
public function me()
{
return response()->json(auth('api')->user());
}
/** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */
public function logout()
{
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/** * Refresh a token. * @return \Illuminate\Http\JsonResponse */
public function refresh()
{
return $this->respondWithToken(auth('api')->refresh());
}
/** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
}
- Model- newly build User
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $table = 'users';
// 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 [];
}
}
end- To this end
版权声明
本文为[Stupid little attendant]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220630238413.html
边栏推荐
- 基于ele封装下拉菜单等组件
- Introduction to ACM [TSP problem]
- Publish to NPM?
- Kubernetes - Introduction to actual combat
- Use of MySQL command line client and common commands
- c#语法糖模式匹配【switch 表达式】
- ele之Table表格的封装
- MYSQL05_ Ordr by sorting, limit grouping, group by grouping
- Specific field information of MySQL export table (detailed operation of Navicat client)
- JSON data text
猜你喜欢
It turns out that PID was born in the struggle between Lao wangtou and Lao sky
tf. keras. layers. Timedistributed function
BLDC double closed loop (speed PI + current PI) Simulink simulation model
Xamarin效果第二十二篇之录音效果
Encapsulation of ele table
Cherno_ Game engine series tutorial (5): 101~
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
Shell script learning notes - regular expressions
Configuring Apache Web services for servers such as Tianyi cloud
AOT和单文件发布对程序性能的影响
随机推荐
Basic workflow of CPU
tf. keras. layers. Density function
Numpy stack function
Introduction and use of openfeign component
Openfeign service call
MYSQL05_ Ordr by sorting, limit grouping, group by grouping
Summary of interface automation interview questions for software testing
Systemctl start Prometheus + grafana environment
Configuring Apache Web services for servers such as Tianyi cloud
Blazor University (12)组件 — 组件生命周期
c#可变参数params的介绍
Small companies don't make formal offers
[Euler plan question 13] sum of large numbers
AC380V drop 5v12v24v200ma, UHV non isolated chip IC scheme
JS relearning
Niuke white moon race 5 [problem solving mathematics field]
tf. keras. layers. Timedistributed function
Passing object type parameters through openfeign
【新版发布】ComponentOne 新增 .NET 6 和 Blazor 平台控件支持
It turns out that PID was born in the struggle between Lao wangtou and Lao sky