搜尋
首頁後端開發php教程如何滿足 API 場景下的授權需求呢?

如何滿足 API 場景下的授權需求呢?

Jun 23, 2017 am 11:46 AM
apilaravel蓋站系統認證

介紹

在 Laravel 中,實作基於傳統表單的登陸和授權已經非常簡單,但是如何滿足 API 場景下的授權需求呢?在 API 場景裡通常透過令牌來實現使用者授權,而非維護請求之間的 Session 狀態。現在 Laravel 專案中可以使用 Passport 輕鬆實現 API 授權流程,透過 Passport 可以在幾分鐘之內為你的應用程式添加完整的 OAuth2 服務端實作。


安裝

使用Composer 依賴套件管理器安裝Passport :

 composer require laravel/passport

接下來,將Passport 的服務提供者註冊到設定文件 config/app.php 的 providers 數組中:

Laravel\Passport\PassportServiceProvider::class

Passport 使用服務提供者註冊內部的資料庫遷移腳本目錄,所以上一步完成後,你需要更新你的資料庫結構。 Passport 的遷移腳本會自動建立應用程式所需的客戶端資料表和令牌資料表:

php artisan migrate

接下來,你需要執行passport:install 指令來建立產生安全存取命令牌時使用的加密金鑰,同時,這條指令也會建立「私人存取」客戶端與「密碼授權」客戶端:

php artisan passport:install

上面指令執行後,修改App\User.php ,用於檢查已認證使用者的令牌和使用作用域:

<?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; // 增加 HasApiTokens

接下來,需要在AuthServiceProvider 的boot 方法中呼叫Passport::routes 函數。這個函數會註冊一些在存取權杖、用戶端、私人存取權杖的發放和撤銷過程中會用到的必要路由:

修改App\Providers\AuthServiceProvider.php :

#
<?php namespace App\Providers;use Laravel\Passport\Passport; // 新增use Illuminate\Support\Facades\Gate;use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;use Carbon\Carbon; // 新增引用class AuthServiceProvider extends ServiceProvider
{/**
     * The policy mappings for the application.
     *
     * @var array     */protected $policies = [&#39;App\Model&#39; => 'App\Policies\ModelPolicy',];/**
     * Register any authentication / authorization services.
     *
     * @return void     */public function boot()
    {$this->registerPolicies();

        Passport::routes(); // 注册passport路由

        //令牌的有效期Passport::tokensExpireIn(Carbon::now()->addDays(15));

        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    }
}

最後,需要將設定檔config/auth.php 中api 部分的授權保護項目( driver )改為passport 。此調整會讓你的應用程式在接收到API 的授權請求時使用Passport 的TokenGuard 來處理:

'guards' => ['web' => ['driver' => 'session',
        'provider' => 'users',],

    'api' => ['driver' => 'passport', // 改为passport'provider' => 'users',],],

測試

##api的路由是api.php 。打開 routes\api.php ,新增測試路由。

Route::group(['namespace' => 'api'], function () {
    Route::post('/login', 'UserController@login');
});

Route::group(['middleware' => 'auth:api', 'namespace' => 'api'], function() {
    Route::get('details', 'UserController@details');
});
一個是用來登錄,取得token,另一個是用取得到的token完成登入驗證,取到目前使用者資料。

details路由,用到了auth:api 中間件,用它來驗證token。

在App\Http\ 目錄建立api 資料夾,並且加入UserController.php 

<?php namespace App\Http\Controllers\api;use Illuminate\Http\Request;use App\Http\Controllers\Controller;use Illuminate\Support\Facades\Auth;use App\User;use Response;class UserController extends Controller
{public function __construct()
    {$this->content = array();
    }public function login()
    {if(Auth::attempt(['email' => request('email'), 'password' => request('password')]))
        {$user = Auth::user();$this->content['token'] =  $user->createToken('Pizza App')->accessToken;$status = 200;
        } else {$this->content['error'] = "未授权";             $status = 401;
        }         return response()->json($this->content, $status);    
    }public function details()
    {return response()->json(['user' => Auth::user()]);
    }
}
在postman 裡測試:

#如上圖所示,登入方法要符合路由,用post方式,以表單方式把使用者的email 與password 傳遞到api/login 

 

如果傳遞正確的話,會得到上圖的token

#把上個步驟得到的token 加入在Header裡,並在token前面加上' Bearer '。然後就可以得到目前使用者的資料了。也就是完成了使用者身份驗證。

 

以上不保證完全正確。歡迎查看我的GitHub的程式碼。

 

以上是如何滿足 API 場景下的授權需求呢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用