安装
运行以下命令把最新版本:
composer require tymon/jwt-auth
#这里可能有个坑 使用这个命令下载的版本并不是最新的??是' ^0.5.12'
#修改composer.json 版本为 '1.0.0-rc.1'
#执行 composer update
将以下代码片段添加到bootstrap/app.php
文件中,是根据包提供商
在服务提供者注册区需改变如下:
// 取消这行注释
$app->register(App\Providers\AuthServiceProvider::class);
// 添加jwt的服务
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
中间件区
//取消auth中间件注释
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
修改过后我的 app.php
文件是这样:(如果像我新下载框架,官方教只是局部文档)
<?php
require_once __DIR__.'/../vendor/autoload.php';
try {
(new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$app->withFacades();
$app->withEloquent();
//config
// jwt
$app->configure('auth');
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
// $app->middleware([
// App\Http\Middleware\ExampleMiddleware::class
// ]);
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
// Add this line
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
使用artisan生成jwt secret key
php artisan jwt:secret
运行这行命令后会在.env文件中生成如 JWT_SECRET=foobar
这里需要额外提的是lumen默认是没有类似llaravel的config配置文件夹的,所有包的配置都是直接去读的.env中的配置。如果想要和laravel一样,自己按照laravel目录结构额外新建一个config文件夹
如生成auth.php,可以把服务提供商中的配置文件拷贝出来或者自己写配置也行。要使配置文件生效,应在bootstrap/app.php
文件中添加
#官方好像没有这一步,但是使用lumen这步也是需要注意的,我是添加了这行,因为我沿用laravel的目录风格
$app->configure('auth');
使用
安装jwt
jwt-auth是专为laravel和lumen量身定制的包,因此必须安装使用这个两者之一
#安装lumen or laravel 使用composer 没有跟版本号,默认安装最新的
composer create-project --prefer-dist laravel/lumen test
#or
composer create-project --prefer-dist laravel/laravel test
composer require tymon/jwt-auth
更新User Model
建议不要框架自带的一个User.php ,在app目录下新建一个Models目录,新建User.php Model 必须满足Tymon\JWTAuth\Contracts\JWTSubject
契约,官方推荐更为为如下,可以根据需求再自定其他功能。
根据官方的 User.php
我做了一下调整,为什么要调整,是为了代码能跑起来
<?php
/**
* Created by PhpStorm.
* User: hony
* Date: 2018/1/19
* Time: 11:57
*/
namespace App\Models;
use Tymon\JWTAuth\Contracts\JWTSubject;
#use Illuminate\Notifications\Notifiable;
#use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements AuthenticatableContract, JWTSubject
{
#use Notifiable;
use Authenticatable;
// 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 [];
}
}
config配置
基于laravel的 config/auth.php
文件需要做一些修改才能使用JWT
的守护,官方提供需要修改如下:
我的 config/auth.php
,如下
<?php
/**
* Created by PhpStorm.
* User: hony
* Date: 2018/1/19
* Time: 14:35
*/
return [
/*
|--------------------------------------------------------------------------
| 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' => '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: "session", "token"
|
*/
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',//这里是因为我用的mysql做的测试
'model' => App\Models\User::class,
],
],
];
这里是告诉应用默认使用api守护,api守护是使用jwt驱动
在身份验证系统里lumen应该使用的是laravel的构建与jwt-auth做幕后的工作!
添加一些基本身份验证路由
在 routes/api.php
添加,也可以做区分
Route::group([
//'middleware' => 'auth',这里本来是api的被我改成auth,但是在登录的时候不需要auth中间件验证
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController@login');
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::post('me', 'AuthController@me');
});
#延伸扩展区分
Route::group(['middleware' => 'token'], function () {
#这个文件中再去指定控制器等
require(__DIR__ . '/api/cases.php');
});
创建AuthController
php artisan make:controller AuthController
#但是lumen本事是没有make:controller命令的,我是手动生成
然后添加内容
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
#这个句是官方提供的,还没有验证是否有效
#$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT token via given credentials.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
/**
* Get the authenticated User
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json($this->guard()->user());
}
/**
* Log the user out (Invalidate the token)
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
$this->guard()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken($this->guard()->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' => $this->guard()->factory()->getTTL() * 60
]);
}
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\Guard
*/
public function guard()
{
return Auth::guard();
}
}
测试登录路由 http://example.dev/auth/login
身份验证响应
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
"token_type": "bearer",
"expires_in": 3600
}
这个令牌可以用来制造经过身份验证的请求,您的应用程序。
验证请求方式 Authenticated requests
There are a number of ways to send the token via http:
Authorization header
Authorization: Bearer eyJhbGciOiJIUzI1NiI…
Query string parameter
http://example.dev/me?token=eyJhbGciOiJIUzI1NiI…
我的请求方式 我使用的是postman
最后,需要最值的注意的是,这个jwt的默认验证方式是hash。