Laravel 5.5 使用 Passport 服务做 API 认证

本教程中我们使用Passport构建了以下API服务

  • Register API
  • Login API
  • Get User Details API

接下来只需按照下面的步骤,我们就能很快速地将Passport集成到您的laravel项目中

1、首先安装,我们需要在项目中运行以下命令安装laravel的Passport软件包

composer require laravel/passport

2、安装成功之后,我们需要设置他们的服务提供者,所以打开config/app.php文件,并在其中添加以下代码

'providers' => [
    '''
    Laravel\Passport\PassprotServiceProvider::class,
],

注: laravel5.5 以上版本可以忽略这一步骤,此步骤争对 5.5 以下版本

3、注册之后,迁移数据表, Passport会生成用于存储客户端和令牌的数据表

php artisan migrate

接下来我们安装 Passport 以生成令牌和客户端

php artisan passport:install

4、完成上面步骤,我们来配置下Passport

  • 打开 模型 app/User.php 我们需要增加 HasApiTokens
  • 打开 app/Providers/AuthServiceProvider.php 中增加 Passport::routers()
  • config/auth.php 中,更改 api 认证方式为 password

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
use Laravel\Passport\RouteRegistrar;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

config/auth.php

return [
    .....
    .....
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    .....
    .....
]

5、配置 routes/api.php 增加相应路由令牌

Route::post('login', 'API\PassportController@login');
Route::post('register', 'API\PassportController@register');

Route::group(['middleware' => 'auth:api'], function(){
    Route::post('get-details', 'API\PassportController@getDetails');
});

6、接下来创建控制器

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 PassportController extends Controller
{

    public $successStatus = 200;

    /**
     * login api
     *
     * @return \Illuminate\Http\Response
     */
    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);
        }
    }

    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    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);
    }

    /**
     * details api
     *
     * @return \Illuminate\Http\Response
     */
    public function getDetails()
    {
        $user = Auth::user();
        return response()->json(['success' => $user], $this->successStatus);
    }
}

到此所有代码编写完成,接下来我们来测试使用它

php artisan serv

1、我们使用 postman 工具来测试 register api
file

2、测试 login api 使用第一步注册的邮箱和密码登录
file

3、使用第二步获取到的 token 值来获取用户信息
file

必须把Token值放到header头部信息里面才行。到此大功告成,需要的朋友可以拿走~

本文章首发在 Laravel China 社区