安装 在
composer.json
中写入以下代码,然后执行composer update
"require-dev": {
"dingo/api" : "1.0.*@dev",
"tymon/jwt-auth": "0.5.*"
},
配置---在
config/app.php中
'providers' => [
Dingo\Api\Provider\LaravelServiceProvider::class,
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
],
'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],
然后执行
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
// 这个可能是生成token的
php artisan jwt:generate
配置
// 在 .env 文件里
API_STANDARDS_TREE=vnd
API_PREFIX=api
API_VERSION=v1
// config/api.php里大概171行的 auth 数组里添加以下配置
'auth' => [
'basic'=> function($app){
return new \Dingo\Api\Auth\Provider\Basic($app['auth']);
},
'jwt' => function($app){
return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
}
],
// config/jwt.php里面 文件使用默认的即可
// 大概第15行的key 是执行 php artisan jwt:generate 的时候自动生成的
'secret' => env('JWT_SECRET', 'a6UeS6HkENOsvmvfSM8ElIiArYjcYIJO'),
// app/Http/Kernel.php里,大概第51行 路由中间件里追加
protected $routeMiddleware = [
'jwt.auth' => \Tymon\JWTauth\Middleware\GetUserFromToken::class,
'jwt.refresh' =>\Tymon\JWTauth\Middleware\RefreshToken::class,
];
使用
- 在路由中添加以下路由
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->group(['namespace'=>'App\Api\Controllers'],function ($api){
$api->get('lessions','LessionController@index');
});
});
// 在控制器中放入测试数据
public function index()
{
return User::all();
}
如果找不到路由,可以执行
composer dump-authload
.我做测试的时候发现整个项目走不通了,但是我运行了php artisan api:routes
又可以了
配置好之后,我们可以参考jwt-auth的Creating Tokens手册
- 做一个
AuthController
验证类
<?php
/**
* Created by PhpStorm.
* User: luanjinlong
* Date: 2017/7/2
* Time: 下午10:35
*/
namespace App\Api\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTauth\Middleware\GetUserFromToken;
class AuthController extends Controller
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
// $credentials = [
// 'user_email' => $request->get('user_email'),
// 'user_password' => $request->get('user_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'));
}
public function register(Request $request)
{
$newUser = [
'email' => $request->get('email'),
'name' => $request->get('name'),
'password' => bcrypt($request->get('password')),
];
$user = User::create($newUser);
// return $user;
$token = JWTAuth::fromUser($user);
return response()->json(compact('token'));
}
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
}
注意,我们在登录的时候,如果自己的用户名密码跟默认laravel
的字段不匹配,我们也可以在authenticate()
函数中重写credentials
变量
$credentials = [
'user_email' => $request->get('user_email'),
'user_password' => $request->get('user_password')
];
我们还得在User类中重写getAuthPassword函数,这个函数是模型自带的
{
return $this->user_password; //此处的user_password是指的我们数据表字段。这样写即可 数据表字段是什么,此处就写什么
}
添加一个方法
$api->post('/user/login','AuthController@authenticate');
,使用postman
做测试
这个时候我们可以带
token
去请求。但是我此处此时并没有成功,可能是我本地的原因吧
http://laravelapi/api/lessions?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjcsImlzcyI6Imh0dHA6Ly9sYXJhdmVsYXBpL2FwaS91c2VyL3JlZ2lzdGVyIiwiaWF0IjoxNDk5MDA5MDU3LCJleHAiOjE0OTkwMTI2NTcsIm5iZiI6MTQ5OTAwOTA1NywianRpIjoiZTd5b0ZmNFJFVUF3NUV4YiJ9.qMjd4QpVHWKsMgdLyhaKtzGhqVaGEbjWKJ-Zoorj954
- 路由
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->group(['namespace'=>'App\Api\Controllers'],function ($api){
$api->post('/user/login','AuthController@authenticate');
$api->post('/user/register','AuthController@register');
// 此处中间件可以使用 jwt.auth,也可以使用 jwt.refresh
$api->group(['middleware'=>'jwt.auth'],function ($api){
$api->get('lessions','LessionController@index');
});
});
});
如果我们想通过
token
去查找用户的信息,可以去访问控制器里面的getAuthenticatedUser
方法
// 路由
$api->get('user/me','AuthController@getAuthenticatedUser');
- 推荐文章
第一篇 https://segmentfault.com/a/1190000004598315
第二篇 https://segmentfault.com/a/1190000004614022
第三篇 https://segmentfault.com/a/1190000004658193
以上信息根绝博客信息测试的,下面的是我自己的测试数据
路由里面
// 访问这个路由会生成一个token
Route::get('/createUserToken','AuthenticateController@createUserToken');
请求 http://laravelapi/createUserToken
控制器里面
public function createUserToken()
{
$user = User::find(3);
$token = JWTAuth::fromUser($user);
return $token;
}
Route::get('/getAuthenticatedUser','getAuthenticatedUser@getAuthenticatedUser');
访问 http://laravelapi/getAuthenticatedUser?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjMsImlzcyI6Imh0dHA6Ly9sYXJhdmVsYXBpL2NyZWF0ZVVzZXJUb2tlbiIsImlhdCI6MTQ5OTUxNDc5MSwiZXhwIjoxNDk5NTE4MzkxLCJuYmYiOjE0OTk1MTQ3OTEsImp0aSI6IldBNUlmdmlEbnp5SkJMTkcifQ.v_yeMa9_hRdz5OKZHWJy6cLPcgOi-Tcf5PZR1n1eEto
<?php
/**
* Created by PhpStorm.
* User: luanjinlong
* Date: 2017/7/8
* Time: 下午7:42
*/
namespace App\Http\Controllers;
use JWTAuth;
class getAuthenticatedUser
{
// somewhere in your controller
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
}
或者我们也可以直接简写
public function getToken()
{
$user = JWTAuth::parseToken()->authenticate() ;
return $user;
}
- 这个时候我们会得到
id=3
用户的数据