laravel8-使用jwt
jwt-官方网址
https://jwt-auth.readthedocs.io/en/develop/laravel-installation
安装
- 第一步:composer拉取最新版本
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
{
/**
* 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-新建 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-到此结束