您的位置:首页 > 编程语言 > PHP开发

laravel 使用JWT实现用户认证

2017-10-10 22:33 696 查看
在laravel使用Token进行用户认证

首先先安装拓展包

composer require tymon/jwt-auth 0.5.*


然后在配置中注册

Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class
.....
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class


发布配置文件生成密钥

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


然后创建注册和登录路由

/routes/web.php

Route::post('/register', 'Auth\RegisterController@register');
Route::post('/login','Auth\LoginController@email');


去控制器创建注册用户方法

app/Http/Controllers/Auth/RegisterController.php
protected function create(array $data){}
public function register(Request $request)
{
$this->validator($request->all())->validate();
//验证的规则

$user = $this->create($request->all());//存数据到数据库
$token = JWTAuth::fromUser($user);
//通过用户对象实例创建token
return ["token" => $token];
}


接下来创建登录的方法,这里我是用邮箱登录

app/Http/Controllers/Auth/LoginController.php

public function email(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'));
}


之后就会得到

{

“token”:”eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cDpcL1wvbG9jYWx

ob3N0OjgwMDFcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNDUxODg4MTE5LCJleHAiOjE0NTQ1MTYxMTksIm5iZiI6MTQ1MTg4OD

}

token可以设置Authorization头来使用:

Authorization: Bearer {yourtokenhere}

也可以放进URL中使用

http://localhost:8001?token={yourtokenhere}

用户完成登录注册之后就可以设置需要登录后才能访问的路由,首先到

app/Http/Kernel.php

protected $routeMiddleware = [
...
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
];


然后就是设置路由

routes/web.php

Route::group(['middleware' => 'jwt.auth', 'providers' => 'jwt'], function () {
Route::post('/test', 'TestController@test');
});


这样就代表在访问/test路由的时候需要带有token,登录才能访问

而获取用户信息则可以在TestController中的test方法中采用

$user = JWTAuth::parseToken()->authenticate();//获取用户信息
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: