laravel8-使用jwt
jwt-官方网址 https://jwt-auth.readthedocs.io/en/develop/laravel-installation
安装
composer require tymon/jwt-auth
- 第二步:添加服务提供者(Laravel 5.4 或以下)
将服务提供者添加到配置文件 config/app.php 中的 providers 数组中,如下所示:
'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 文件,允许配置此包的基础知识
php artisan jwt:secret
运行完后.env文件会生成一个 JWT_SECRET
在laravel项目中配置
- 第一步:配置 config/auth.php
在 config/auth.php 中,将 api 的 driver 驱动改为 jwt 然后注册自己写的model - 第二步:定义路由 具体代码 - 控制器-新建 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
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
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);
}
public function me()
{
return response()->json(auth('api')->user());
}
public function logout()
{
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}
public function refresh()
{
return $this->respondWithToken(auth('api')->refresh());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
}
- Model-新建 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';
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
end-到此结束
|