本教程中我們使用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\PassportServiceProvider::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
2、測試 login api
使用第一步註冊的郵箱和密碼登入
3、使用第二步獲取到的 token
值來獲取使用者資訊
必須把Token值放到header頭部資訊裡面才行。到此大功告成,需要的朋友可以拿走~
本作品採用《CC 協議》,轉載必須註明作者和本文連結