-
Notifications
You must be signed in to change notification settings - Fork 12
JWT
turtle edited this page Feb 26, 2016
·
1 revision
JWT(JSON WEB TOKEN)一种API验证方式,详情请见JWT
Note:在该Laravel5.2框架中已经安装并配置好了JWT,可以直接使用。
使用
在app/Api/V1/Controllers下新建Auth文件夹,在Auth文件夹下面新建AuthController.php文件
<?php
namespace App\Api\V1\Controllers\Auth;
use App\Api\V1\Controllers\BaseController;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\User;
class AuthController extends BaseController {
public function authenticate(Request $request) {
// grab credentials from the request
$credentials = $request->only('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'));
}
}
注册路由,在Auth文件夹下新建routes.php文件
/*
* Auth Controller Routes
*
*/
$api->post('/auth/login', 'Auth\AuthController@authenticate');
修改app/Api/V1/routes.php文件,引入Auth/routes.php文件
$api->version('v1', function ($api) {
$api->group(['namespace' => 'App\Api\V1\Controllers'], function($api) {
/*
* include controller routes
*/
$dir = '/var/www/dingo/app/Api/V1/Controllers/';
// Auth Controller Rotues
require_once $dir.'Auth/routes.php';
// User Controller Routes
require_once $dir.'User/routes.php';
});
});
访问链接www.example.com/api/auth/login,登陆成功可以返回一串token值。可以结合register方法,先注册一个测试用户。
在AuthController.php中加入
public function register(Request $request) {
$newUser = [
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password')),
];
$user = User::create($newUser);
$token = JWTAuth::fromUser($user);
return response()->json(compact('token'));
}
修改该目录下的routes.php,注册/auth/register路由
$api->post('/auth/login', 'Auth\AuthController@authenticate');
$api->post('/auth/register', 'Auth\AuthController@register');
可以在一个路由或路由组中使用jwt.auth中间件,通过token来验证获取资源的权限。
$api->group(['middleware' => 'jwt.auth'], function($api) {
$dir = '/var/www/dingo/app/Api/V1/Controllers/';
// User Controller Routes
require_once $dir.'User/routes.php';
});
当访问www.example.com/api/user/all时,需要在加上Header Authorization: Bearer {yourtokenhere}。