Laravel使用Passport来创建API用户认证
比如说你要给你的手机APP用户创建API,使用的是你已有的Laravel系统里的数据库,尤其是用户数据。现在我们来看一下,这里使用的是Laravel Passport组件。
我们将要创建三个api,分别是:
Login API
Register API
Details API
(一)安装和配置Passport
composer require laravel/passport
在 config/app.php 中注册 provider:
'providers' => [
....
Laravel\Passport\PassportServiceProvider::class,
],
创建Passport需要的数据表:
php artisan migrate
然后初始化Passport,执行:
php artisan passport:install
该命令会生成用以后期创建安全令牌(access token)的秘钥,同时也会创建personal access和password grant两个客户端(clients)。
接下来,在 app/User.php 中添加 HasApiTokens trait:
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
然后在 app/Providers/AuthServiceProvider.php 中添加 Passport::routes();:
<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
...
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
在 config/auth.php 中将 api 的 driver 改成 passport:
<?php
return [
.....
'guards' => [
...
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
.....
]
(二)创建相应的api路由
在你的 routes/api.php 中
Route::post('login', 'API\UserController@login');
Route::post('register', 'API\UserController@register');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController@details');
});
(三)创建相应的controller
路径 app/Http/Controllers/API/UserController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class UserController extends Controller
{
public $successStatus = 200;
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success'=>$success], $this->successStatus);
}
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
}
(四)我们使用 postman 工具来测试
1、测试注册API (register api)
2、测试 login api 使用第一步注册的邮箱和密码登录
3、使用第二步获取到的 token 值来获取用户信息
Details API:
这个测试前需要添加一些header信息:
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
必须把 Token 值放到 header 头部信息里面才行。
[译文出处]:
itsolutionstuff.com/post/laravel-5-how-to-create-api-authentication-using-passport-example.html
错误解决
遇到
"message": "Failed to authenticate because of bad credentials or an invalid authorization header.",
"status_code": 401,
"debug": {
"line": 113,
"file": "G:\\WWW\\renwubao\\vendor\\dingo\\api\\src\\Auth\\Auth.php",
"class": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
修改 config/api.php
'auth' => [
'jwt' => 'Dingo\Api\Auth\Provider\JWT',
],
PHP Fatal error: Uncaught Error: Call to a member function connection() on null in G:\WWW\renwubao\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1249
遇到错误
"message": "Class Tymon\\JWTAuth\\JWTAuth does not exist",
"exception": "ReflectionException",
"file": "G:\\WWW\\renwubao\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 851,
composer require tymon/jwt-auth