lumen5.4整合dingo/api、jwt-auth
来源:互联网 发布:杯子软件测试例子 编辑:程序博客网 时间:2024/06/06 09:34
一、版本说明,composer.json文件如下:
二、安装lumen (https://lumen.laravel-china.org/)
1、执行命令:composer create-project --prefer-dist laravel/lumen api ,新建一个lumen api项目
2、配置nginx vhost,内容如下:
server {
listen 80;
server_name api.lumen.tangzw.com;
root D:/workspace/lumen/api/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php($|/){
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}
3、修改lumen配置文件(.env)
设置一个32位的APP_KEY,其他配置(如数据库配置)根据自己的实际情况进行配置
4、在浏览器中访问看到Lumen (5.4.3) (Laravel Components 5.4.*)的输出,说明lumen安装成功
二、整合dingo/api (https://github.com/dingo/api)
1、在composer.json中的require下添加 “dingo/api”: "1.0.*@dev",执行composer update命令安装dingo/api扩展包
2、配置dingo/api,可参照dingo/api的github上的wiki页面,我的配置如下(.env):
#dingo api
API_STANDARDS_TREE=vnd
API_PREFIX=api
API_STRICT=false
API_DEBUG=true
API_VERSION=v1
API_SUBTYPE=lumen
3、找到 文件中的Register Service Providers项,添加 $app->register(Dingo\Api\Provider\LumenServiceProvider::class);
4、到这一步dingo/api已经安装完成,我们可以写两个demo测试一下,打开路由文件(routes/web.php)添加如下路由:
//Dingo API 路由
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', ['namespace' => 'App\Http\Controllers\V1'], function($api){
//测试
$api->get('test', function(){
return 'hi Evan';
});
});
$api->version('v2', ['namespace' => 'App\Http\Controllers\V2'], function($api){
//测试
$api->get('test', function(){
return 'hi Tang Zhao Wen';
});
});
使用postman访问测试,可以通过设置不同的Accept值访问不同版本的接口(Accep:tapplication/vnd.{API_SUBTYPE}.{VERSION}+json)
a、访问V1版接口
b、访问V2版接口
三、整合JWT-Auth (https://github.com/tymondesigns/jwt-auth)
1、在composer.json中的require下添加 "tymon/jwt-auth": "1.0.*@dev",执行composer update命令安装jwt-auth扩展包,目前稳定版为0.5,由于0.5对lumen5.4不太兼容,会 出现很多问题,所以这里使用最新的1.0版(非稳定版)
2、修改bootstrap/app.php文件:
a、去掉$app->withFacades();前的注释
b、去掉$app->withEloquent();前的注释
c、找到 Register Service Providers项,添加 $app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
6、执行php artisan jwt:secret 命令生成jwt的secret
7、在项目根目录下 新建一个config目录,复制vendor/laravel/lumen-framework/config/auth.php到config目录下,修改内容如下:
<?phpreturn [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */'defaults' => [ 'guard' => env('AUTH_GUARD', 'api'),'passwords' => 'users',],/* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "token" | */'guards' => [ 'api' => [ 'driver' => 'jwt','provider' => 'users'],],/* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */'providers' => [ 'users' => [ 'driver' => 'eloquent','model' => \App\User::class,],],/* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | Here you may set the options for resetting passwords including the view | that is your password reset e-mail. You may also set the name of the | table that maintains all of the reset tokens for your application. | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */'passwords' => [ //],];
<?phpnamespace App;use Illuminate\Auth\Authenticatable;use Laravel\Lumen\Auth\Authorizable;use Illuminate\Database\Eloquent\Model;use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;use Tymon\JWTAuth\Contracts\JWTSubject;class User extends Model implements JWTSubject, AuthenticatableContract, AuthorizableContract{ use Authenticatable, Authorizable;protected $table = 'users';/** * The attributes that are mass assignable. * * @var array */protected $fillable = [ 'name', 'email',];/** * The attributes excluded from the model's JSON form. * * @var array */protected $hidden = [ 'password',];public function getJWTIdentifier() { return $this->getKey();} public function getJWTCustomClaims() { return [];}}
9、修改app/Providers/AuthServiceProvider.php
<?phpnamespace App\Providers;use App\User;use Illuminate\Support\Facades\Gate;use Illuminate\Support\ServiceProvider;class AuthServiceProvider extends ServiceProvider{ /** * Register any application services. * * @return void */public function register() { //} /** * Boot the authentication services for the application. * * @return void */public function boot() { // Here you may define how you wish users to be authenticated for your Lumen // application. The callback which receives the incoming request instance // should return either a User instance or null. You're free to obtain // the User instance via an API token or any other method necessary.$this->app['auth']->viaRequest('api', function ($request) { return \App\User::where('email', $request->input('email'))->first();});}}
10、编写一个类获取token
<?php
/** * JWT权限控制* Author: Evan <tangzwgo@gmail.com> * Since: 2017/2/9 */namespace App\Http\Controllers\Auth;use App\Http\Controllers\BaseController;use Illuminate\Http\Request;use Tymon\JWTAuth\JWTAuth;use Tymon\JWTAuth\Exceptions\TokenExpiredException;use Tymon\JWTAuth\Exceptions\TokenInvalidException;use Tymon\JWTAuth\Exceptions\JWTException;class AuthenticateController extends BaseController{ /** * @var \Tymon\JWTAuth\JWTAuth */protected $jwt;public function __construct(JWTAuth $jwt) { $this->jwt = $jwt;} /** * 获取token * @param Request $request * @return \Illuminate\Http\JsonResponse */public function authenticate(Request $request) { $this->validate($request, [ 'email' => 'required|email|max:255','password' => 'required',]);try { if (! $token = $this->jwt->attempt($request->only('email', 'password'))) { return response()->json(['user_not_found'], 404);} } catch (TokenExpiredException $e) { return response()->json(['token_expired'], 500);} catch (TokenInvalidException $e) { return response()->json(['token_invalid'], 500);} catch (JWTException $e) { return response()->json(['token_absent' => $e->getMessage()], 500);} return response()->json(compact('token'));}}
11、添加一个路由
$api->version(['v1', 'v2'], ['namespace' => 'App\Http\Controllers\Auth'], function($api){ //获取token$api->post('auth/token', 'AuthenticateController@authenticate');});
12、测试
- lumen5.4整合dingo/api、jwt-auth
- Lumen上使用Dingo/Api做API开发时用JWT-Auth做认证的实现
- Lumen上使用Dingo/Api做API开发时用JWT-Auth做认证的实现
- Lumen上使用Dingo/Api做API开发时用JWT-Auth做认证的实现
- laravel 5.4 JWT + Dingo 构建API 攻略
- Laravel 5 开发API(Dingo Api + JWT)
- Dingo + Laravel + JWT + Entrust + memcache 实现API设计
- Laravel实现dingo+JWT api接口之配置篇
- Laravel实现dingo+JWT api接口之实战篇
- Laravel实现dingo+JWT api接口之配置篇
- How to implement JWT Auth About Restful API in Laravel 5.5
- Laravel-dingo/api获取路由
- 转--dingo/api扩展包
- 在Laravel5.2中使用dingo+JWT+Swagger
- RuntimeError at /jwt-auth django rest_framework
- api安全-----oauth2&jwt
- Lumen 配合使用Dingo/Api的问题。
- laravel dingo/api 安装与配置
- 怎么运行npm本地安装的模块
- 练习:使用springmvc实现H5(server-sent event)
- java面试题全集(下)
- Storyboard (一)
- iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD
- lumen5.4整合dingo/api、jwt-auth
- 骑士周游问题解决方案
- html第一次课作业
- 如何判断一款app使用原生实现,还是Hybrid APP
- Python 之 zip,map,lambda
- mysql数据库数据的删除与恢复
- 前端的网址&资源
- 防止ViewPager中的Fragment被销毁的方法
- $.inArray()方法类似于JavaScript的原生.indexOf()方法