詳解Laravel5.6 Passport實(shí)現(xiàn)Api接口認(rèn)證
很多企業(yè)做項(xiàng)目使用前后端分離,后端提供接口地址,前端使用接口地址拿數(shù)據(jù),并渲染頁面。那么,前端用戶登錄如何使用接口進(jìn)行認(rèn)證?網(wǎng)上各種教程寫的不堪入目,完全看不懂,所以我根據(jù)自己的理解,寫下此篇文章,希望能幫助到大家。
后端(Laravel5.6框架)
1、使用 composer 安裝 Passport ,打開終端,執(zhí)行命令:
composer require laravel/passport #安裝完成后,在composer.json文件中會(huì)看到文件版本信息
2、接下來,將 Passport 的服務(wù)提供者注冊(cè)到配置文件 config/app.php 的 providers 數(shù)組中
Laravel\Passport\PassportServiceProvider::class,
3、執(zhí)行數(shù)據(jù)庫遷移
php artisan migrate #數(shù)據(jù)庫中會(huì)生成接口認(rèn)證所需的5張表
4、創(chuàng)建密碼授權(quán)客戶端
php artisan passport:client --password #創(chuàng)建了client_id和client_secret,前端登錄驗(yàn)證的時(shí)候必須把這兩個(gè)玩意兒帶著
5、獲取keys
php artisan passport:keys
6、配置路由
打開服務(wù)提供者 AuthServiceProvider , 在 boot 方法中加入如下代碼:
use Laravel\Passport\Passport;
public function boot() {
$this->registerPolicies();
Passport::routes(); //接口認(rèn)證的路由
}
然后將配置文件 config/auth.php 中授權(quán)看守器 guards 的 api 的 driver 選項(xiàng)改為 passport
我這里的 customer 表是前端用戶表,但是 laravel 默認(rèn)的是 user 表,所以這里需要做如下配置:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'customers',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => App\Models\Shop\Customer::class,
],
],
7、注冊(cè)中間件,在 app/Http/Kernel.php 文件中的 $routeMiddleware 數(shù)組中添加如下中間件
protected $routeMiddleware = [ 'client.credentials'=>\Laravel\Passport\Http\Middleware\CheckClientCredentials::class, ];
然后在需要認(rèn)證接口路由文件 routes/api.php 前面加上這個(gè)中間件。
Route::group(['prefix' => 'cart', 'middleware' => ['client.credentials']], function () {
...
});
8、前端用戶表 customer 模型里面做如下配置:
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class Customer extends Authenticatable
{
use HasApiTokens;
....
}
至此,后端的所有配置已完成。
接下來,打開接口測(cè)試工具(postman),輸入接口地址: wechat.test/oauth/token ,請(qǐng)求類型 POST ,填上如下參數(shù),點(diǎn)擊 send 你會(huì)看到后臺(tái)返回了前端所需的 access_token :
前端(vue.js)
首先去加載用戶登錄組件,即用戶登錄頁面。
1. 配置路由,在 index.js 文件中寫入如下代碼
import Login from '@/components/customer/Login'
export default new Router({
routes: [
....
{
path: '/customer/login',
name: 'Login',
component: Login
},
]
})
2、加載組件,在 customer 文件夾的 Login.vue 文件中寫入如下代碼:
<template>
<div>
<input type="email" v-model="customer.email" placeholder="請(qǐng)輸入郵箱">
<input type="password" v-model="customer.password" placeholder="請(qǐng)輸入密碼">
<button @click.prevent="submit">登 錄</button>
</div>
</template>
<script>
export default {
data() {
return {
customer: {
email: '',
password: ''
}
}
},
methods: {
submit() {
//將數(shù)據(jù)配置好
const data = {
grant_type: 'password', //oauth的模式
client_id: 1, //上面所說的client_id
client_secret: 'CO331cA1mqiKgGvvgiDzPxh4CUu19vSEiqxM7LHD',//同上
username: this.customer.email,
password: this.customer.password,
}
this.axios.post('/oauth/token', data)
.then(res => {
if (res.status == 200) { //如果成功了,就把a(bǔ)ccess_token存入localStorage
localStorage.token_type = res.data.token_type
localStorage.access_token = res.data.access_token
this.$router.push({name:'Index'})
}
})
}
}
}
</script>
客戶端查看 localStorage ,如圖:

3、在 http.js 文件中設(shè)置攔截器,用于判斷用戶是否登錄,若沒有登錄跳轉(zhuǎn)到登錄頁面。代碼如下:
//#創(chuàng)建http.js文件
import axios from 'axios'
import router from '@/router'
// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'http://wechat.test/';
// http request 攔截器
axios.interceptors.request.use(
config => { //將所有的axios的header里加上token_type和access_token
config.headers.Authorization = `${localStorage.token_type} ${localStorage.access_token}`;
return config;
},
err => {
return Promise.reject(err);
});
// http response 攔截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
// 401 清除token信息并跳轉(zhuǎn)到登錄頁面
if (error.response.status == 401) {
alert('您還沒有登錄,請(qǐng)先登錄')
router.replace({ //如果失敗,跳轉(zhuǎn)到登錄頁面
name: 'Login'
})
}
return Promise.reject(error.response.data)
});
export default axios;
重新訪問項(xiàng)目,在商品詳情頁面點(diǎn)擊加入購物車,你會(huì)發(fā)覺奇跡已經(jīng)出現(xiàn),當(dāng)你沒有登錄時(shí),提示跳轉(zhuǎn)到登錄頁面。輸入賬號(hào)密碼,登錄成功,此時(shí)就能拿到用戶id。接下來,繼續(xù)測(cè)試。
4、去 Cart 控制器中,找到購物車首頁方法,獲取用戶的id,獲取方式如下:
$customer_id = auth('api')->user()->id;
return $customer_id;
5、在 postman 中輸入購物車首頁接口地址,并傳入所需參數(shù),參數(shù)參考地址: http://laravelacademy.org/post/8909.html ,如圖:


拿到用戶id后,把后端之前定義的customer_id全部改為通過接口方法獲取。至此, Passport 接口認(rèn)證的全部操作已完成。
總結(jié):接口認(rèn)證邏輯思想
1、安裝passport后,生成client_id和 client_secret
2、使用username、password、client_id、client_secret、grant_type參數(shù),調(diào)用/oauth/token接口,拿到access_token
3、需要認(rèn)證的接口,加上中間件。這時(shí)候直接訪問接口地址,會(huì)提示沒有認(rèn)證的。帶上access_token后,才能拿到接口的數(shù)據(jù)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Laravel5.1 框架模型工廠ModelFactory用法實(shí)例分析
這篇文章主要介紹了Laravel5.1 框架模型工廠ModelFactory用法,結(jié)合實(shí)例形式分析了laravel5.1框架模型工廠ModelFactory基本功能、定義與使用方法,需要的朋友可以參考下2020-01-01
詳解php中serialize()和unserialize()函數(shù)
這篇文章主要介紹了php的serialize()函數(shù)和unserialize()函數(shù)的相關(guān)資料,需要的朋友可以參考下2017-07-07
PHP實(shí)現(xiàn)登錄驗(yàn)證碼校驗(yàn)功能
這篇文章主要為大家詳細(xì)介紹了PHP實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能,主要是利用PHP中的 SESSION功能來實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
php腳本運(yùn)行時(shí)的超時(shí)機(jī)制詳解
在我們平常的開發(fā)中,也許曾經(jīng)都遇到過PHP腳本運(yùn)行超時(shí)的情況,當(dāng)遇到這種情況我們經(jīng)常會(huì)通過使用 set_time_limit(非安全模式),或修改配置文件并重啟服務(wù)器,或者修改程序減少程序的執(zhí)行時(shí)間,使其在允許的范圍之內(nèi),以解決此問題。2016-02-02
laravel excel 上傳文件保存到本地服務(wù)器功能
今天小編就為大家分享一篇laravel excel 上傳文件保存到本地服務(wù)器功能,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11
linux系統(tǒng)下php安裝mbstring擴(kuò)展的二種方法
這篇文章主要介紹了linux系統(tǒng)環(huán)境下,php安裝mbstring擴(kuò)展的二種方法,大家參考使用吧2014-01-01
php-beanstalkd消息隊(duì)列類實(shí)例分享
這篇文章主要為大家分享了php-beanstalkd消息隊(duì)列類實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07

