laravel基于jwt构建RESTful Api

admin 2017/10/11 17:15:08 928

(1). 新建项目

composer create-project --prefer-dist laravel/laravel laravel-api

(2). 安装jwt扩展包和cors扩展包,在composer.json中添加以下依赖,然后执行composer install

"require": {
        "barryvdh/laravel-cors": "^0.9.3",
        "tymon/jwt-auth": "1.0.0-rc.1"
    },

(3). 项目根目录执行命令

php artisan jwt:secret

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

(4). 打开config配置目录,配置cors.php

'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Auth-Token', 'Origin'],
    'allowedMethods' => ['GET','POST', 'PUT','DELETE','OPTIONS'],
    'exposedHeaders' => [],
    'maxAge' => 0,

(5). 注册中间件

'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
'cors'=> \Barryvdh\Cors\HandleCors::class,

(6). 添加路由

Route::group(['namespace'=>'One','prefix'=>'one','middleware'=>'cors'],function (){
    Route::post('register','UserController@register');
    Route::post('login','UserController@login');
    Route::get('refresh','UserController@refresh');
    Route::get('logout','UserController@logout');

Route::group([‘middleware’=>‘jwt.auth’],function (){
Route::get(’/posts’,‘PostController@index’);
Route::get(’/posts/{id}’,‘PostController@show’)->where(‘id’,’\d+’);
Route::post(’/posts’,‘PostController@store’);
Route::put(’/posts/{id}’,‘PostController@update’)->where(‘id’,’\d+’);
Route::delete(’/posts/{id}’,‘PostController@destroy’)->where(‘id’,’\d+’);
});
});

(7). 相关图片

登录获取token

login

刷新token

refresh

文章列表

article

(8). 参考资料

什么是jwt:jwt
jwt和oauth:jwt和oauth
RESTful APi:RESTful API

(9). 总结

这个demo较为完整的实现了RESTful api的思想,当然还有很多不足的地方,你可以在这个的基础上进行二次开发,譬如多用户jwt认证等,完整的项目托管在码云,如果你有更好的idea,欢迎留言交流。

转载请注明出处!谢谢!



标签
评论一下

评论列表

  • 1 评论:
666
  • 2017/10/14 14:49:15
  • 回复