項目初始化
新建項目
lukeyans-MacBook-Pro:laravel lukeyan$ laravel new laravel_demo
添加laravel自帶的Passport服務(wù)
lukeyans-MacBook-Pro:laravel_demo lukeyan$ composer require laravel/passport
接下來,將 Passport 的服務(wù)提供者注冊到配置文件 config/app.php 的 providers 數(shù)組中:
Laravel\Passport\PassportServiceProvider::class,
在.env 文件配置好數(shù)據(jù)鏈接鬼吵,因為我本地的數(shù)據(jù)庫版本是
服務(wù)器: Localhost via UNIX socket
服務(wù)器類型: MariaDB
服務(wù)器版本: 10.1.16-MariaDB - Source distribution
laravel 5.4 改變了默認(rèn)的數(shù)據(jù)庫字符集,現(xiàn)在utf8mb4包括存儲emojis支持篮赢。
而我的版本比較低一點(高于 10.2.2 版本的不需要理會)齿椅,不支持,得修改一下字符串的長度启泣。
修改
在 AppServiceProvider.php 文件里的 boot 方法里設(shè)置一個默認(rèn)值
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema; //新增的
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191); //新增的
}
}
Passport 使用服務(wù)提供者注冊內(nèi)部的數(shù)據(jù)庫遷移腳本目錄加派,所以上一步完成后悔常,你需要更新你的數(shù)據(jù)庫結(jié)構(gòu)。Passport 的遷移腳本會自動創(chuàng)建應(yīng)用程序需要的客戶端數(shù)據(jù)表和令牌數(shù)據(jù)表:
php artisan make:auth //先生成基礎(chǔ)的用戶數(shù)據(jù)庫表
php artisan migrate //再更新
接下來,你需要運行 passport:install 命令來創(chuàng)建生成安全訪問令牌時用到的加密密鑰票腰,同時闻蛀,這條命令也會創(chuàng)建「私人訪問」客戶端和「密碼授權(quán)」客戶端:
php artisan passport:install
上面命令執(zhí)行后,請將 Laravel\Passport\HasApiTokens Trait 添加到 App\User 模型中,這個 Trait 會給你的模型提供一些輔助函數(shù)险耀,用于檢查已認(rèn)證用戶的令牌和使用作用域:
<?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;
}
接下來,需要在 AuthServiceProvider 的 boot 方法中調(diào)用 Passport::routes 函數(shù)玖喘。這個函數(shù)會注冊一些在訪問令牌甩牺、客戶端、私人訪問令牌的發(fā)放和吊銷過程中會用到的必要路由:
<?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
{
/**
* 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 中 api 部分的授權(quán)保護項( driver )改為 passport 柴灯。此調(diào)整會讓你的應(yīng)用程序在接收到 API 的授權(quán)請求時使用 Passport 的 TokenGuard 來處理:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
接下來,增加API的路由费尽,好實現(xiàn)用戶的
- 新增
- 登錄
- 查看詳情的功能
打開 routes/api.php 文件添加
<?php
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'API\UserController@login');
Route::post('register', 'API\UserController@register');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController@details');
});
接著增加控制器赠群,在APP/HTTP/Controller 目錄新增一個專門的API文件夾放
lukeyans-MacBook-Pro:laravel_demo lukeyan$ php artisan make:controller Api/UserController
增加對應(yīng)路由指向的api的方法
<?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;
/**
* 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 details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
}
好的,開始測試一下旱幼,我一般使用的調(diào)試工具是 postman
1. 注冊
2.登錄
3.獲取詳情(需要注意一下查描,post提交時候需要配置一下 Headers)
格式為
Accept:application/json
Authorization:Bearer+空格+access_token
這樣說明API的認(rèn)證和測試正常啦