Laravel使用Passport来创建API用户认证

hengqiaqia 2019-06-26

本文来自pilishen.com----原文链接; 欢迎作客我们的php&Laravel学习群:109256050

比如说你要给你的手机APP用户创建API,使用的是你已有的Laravel系统里的数据库,尤其是用户数据。现在我们来看一下,这里使用的是Laravel Passport组件。

我们将要创建三个api,分别是:

  1. Login API
  2. Register API
  3. 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 accesspassword 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中将apidriver改成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);
    }
}

(四)使用rest client来测试api

Login API:

Laravel使用Passport来创建API用户认证

Register API:

Laravel使用Passport来创建API用户认证

Details API:

这个测试前需要添加一些header信息:

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
]

Laravel使用Passport来创建API用户认证

[译文出处:
//itsolutionstuff.com/post/laravel-5-how-to-create-api-authentication-using-passport-example.html](//itsolutionstuff.com/post/laravel-5-how-to-create-api-authentication-using-passport-example.html)

相关推荐