转载:https://laravel-china.org/articles/10885/full-use-of-jwt
参考:http://laravelacademy.org/post/8650.html
(1)composer引入jwt
composer require tymon/jwt-auth 1.0.0-rc.2
(2)修改config下auth.php 将api->driver设为jwt(默认是token)
(3)执行下面这个命令会在config文件夹生成jwt.php
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
(4)下面这个这一定要执行 生成秘钥
php artisan jwt:secret
(n)补充路由文件 api.php
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::any('login', 'AuthController@login');
Route::any('logout', 'AuthController@logout');
Route::any('refresh', 'AuthController@refresh');
Route::any('me', 'AuthController@me');
});
(5)在User.php (laravel自带的http 下model文件)改成如下代码
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject # 这里别忘了加
{
use Notifiable;
// 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 [];
}
}
(6)新建 AuthController.php (php artisan make:controller AuthController) AuthController.php插入如下代码
<?php
namespace App\Http\Controllers;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Http\Controllers\Controller;
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()
{
$credentials = request(['email', 'password']);
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->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()->factory()->getTTL() * 60
]);
}
}
(7) 执行php artisan migrate 生成user表 预先在表里插入数据 免去注册
字段email:12345678@qq.com
字段 password: $2y$10$O.AnZd9lr47eBV.C0trqse79b0ELrxo/zNcDFi9uU2pavwquAjfZK
(8) 在postman 里测试 authController 里的login方法
测试数据email:12345678@qq.com password:123456
正确返回结果:{"token":"**************************"}
亲测可用