JWT 完整使用详解(中文)
https://laravel-china.org/articles/10885/full-use-of-jwt#45cd45
JWT 详解(英文)
https://jwt-auth.readthedocs.io/en/develop/laravel-installation/
创建 Laravel 工程
$ composer create-project laravel/laravel xyg 5.6 --prefer-dist
$ php artisan migrate (创建数据库)
一、安装
1. 到官网 :https://github.com/tymondesigns/jwt-auth
查询 Laravel 不同版本对应的 jwt-auth 的不同版本号,使用以下安装命令
$ composer require tymon/jwt-auth 1.0.0-rc.2
config/app.php
...
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
...
'aliases' => [
...
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
]
2. 发布配置文件
$ php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
3. 生成加密密钥 创建RegisterFormRequest
$ php artisan jwt:secret
$ php artisan make:request RegisterFormRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterFormRequest extends FormRequest{
public function authorize(){
return true;
}
public function rules(){
return [
'name' => 'required|string|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:6|max:10',
];
}
}
4. 修改 config/auth.php
'defaults' => [
'guard' => 'api', // 原来是 web 改成 api
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt', // 原来是 token 改成 jwt
'provider' => 'users',
],
],
5. 更新 app/User.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;
protected $fillable = [
'name', 'email', //'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function getJWTIdentifier(){
return $this->getKey();
}
public function getJWTCustomClaims(){
return [];
}
}
6. 创建 token 控制器,在 App\Http\Controllers 文件夹下增加了 AuthController
$ php artisan make:controller AuthController
namespace App\Http\Controllers;
use App\Http\Requests\RegisterFormRequest;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Http\Request;
use App\User;
class AuthController extends Controller{
//RegisterFormRequest 是表单提交,postman选择Body -> x-www-form-urlencoded,输入参数
public function register(RegisterFormRequest $request){
$user = new User;
$user->email = $request->email;
$user->name = $request->name;
$user->password = bcrypt($request->password);
$user->save();
return response([
'status' => 'success',
'data' => $user
], 200);
}
public function login(Request $request){
$credentials = $request->only('email', 'password');
if (!$token = JWTAuth::attempt($credentials)) {
return response([
'status' => 'error',
'error' => 'invalid.credentials',
'msg' => 'Invalid Credentials.'
], 400);
}
return response([
'status' => 'success',
'token' => $token
]);
}
public function user(Request $request){
$user = User::find(Auth::user()->id);
return response([
'status' => 'success',
'data' => $user
]);
}
/**
* Log out
* Invalidate the token, so user cannot use it anymore
* They have to relogin to get a new token
* @param Request $request
*/
public function logout(Request $request) {
$this->validate($request, ['token' => 'required']);
try {
JWTAuth::invalidate($request->input('token'));
return response([
'status' => 'success',
'msg' => 'You have successfully logged out.'
]);
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response([
'status' => 'error',
'msg' => 'Failed to logout, please try again.'
]);
}
}
public function refresh(){
return response([
'status' => 'success'
]);
}
}
7. 注册一些路由。注意:在 Laravel 下,route/api.php 中的路由默认都有前缀 api 。
Route::post('signup', 'AuthController@register');
Route::post('login', 'AuthController@login');
Route::group(['prefix' => 'auth', 'middleware' => 'jwt.auth'], function () {
Route::get('user', 'AuthController@user');
Route::post('logout', 'AuthController@logout');
});
Route::middleware('jwt.refresh')->get('/token/refresh', 'AuthController@refresh');
二、使用
必须先注册才能登陆,直接在数据库添加数据无效,使用postman访问如下接口:
localhost:8888/public/api/signup 输入 name email password 三个参数
再访问,可以获取token
localhost:8888/public/api/login 输入 email password 二个参数
搜索 jwt-auth laravel 5.6
网友评论