首先安装Laravel,然后安装Tymon包:
composer require tymon/jwt-auth
添加以下到config/app.php:
'aliases' => Facade::defaultAliases()->merge([
'Jwt' => Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
])->toArray(),
也可以在提供商数组中添加以下内容:
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
现在发布必要的文件:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
运行迁移:
php artisan migrate
生成一个JWT令牌,将保存在.env
中
php artisan jwt:secret
将以下内容添加到守卫阵列中的API数组:
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
现在在路由/api.php中创建一些路由
Route::middleware(['api'])->group(function() {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::get('/getaccount, [AuthController::class, 'getaccount']);
});
修改用户模型以使用JWT功能:
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
最后修改authcontroller:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use JWTAuth;
use Illuminate\Http\Request;
class AuthController extends Controller
{
//
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);//login, register methods won't go through the api guard
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => Hash::make($request->get('password')),
]);
$token = JWTAuth::fromUser($user);
return response()->json([
'message' => 'User successfully registered',
'user' => $user,
'token' => $token,
], 200);
}
public function getaccount()
{
return response()->json(auth()->user());
}
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60 //mention the guard name inside the auth fn
]);
}
}
登录响应:
注册响应:
GetAccount Repons:
有关包装的更多信息,请咨询文档:
https://jwt-auth.readthedocs.io/en/develop/auth-guard/
上述所有代码均已在Laravel 10.0上进行了尝试和测试,
如果对您有所帮助,请丢弃。 ð