首頁 > php框架 > Laravel > 主體

Laravel Passport 建置 API 驗證和授權

Guanhui
發布: 2020-06-10 09:30:37
轉載
3091 人瀏覽過

Laravel Passport 建置 API 驗證和授權

第一步

執行下列指令:

composer require laravel/passport
php artisan migrate
php artisan passport:install
登入後複製

#修改config/auth.php 檔案中的Gurds:

...
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
...
登入後複製

第三步驟

app/User.php

<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable {
    use Notifiable, HasApiTokens;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        &#39;name&#39;, &#39;email&#39;, &#39;password&#39;,
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        &#39;password&#39;, &#39;remember_token&#39;,
    ];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        &#39;email_verified_at&#39; => &#39;datetime&#39;,
    ];
}
登入後複製

第四步

app/Repositories/User/UserRepositoryInterface.php

<?php
namespace App\Repositories\User;
use Illuminate\Http\Request;
interface UserRepositoryInterface {
    public function register(Request $request);
    public function login(Request $request);
    public function refreshToken(Request $request);
    public function details();
    public function logout(Request $request);
    public function response($data, int $statusCode);
    public function getTokenAndRefreshToken(string $email, string $password);
    public function sendRequest(string $route, array $formParams);
    public function getOClient();
}
登入後複製

第五步

建立app/Repositories/User /UserRepository.php 檔案

<?php
namespace App\Repositories\User;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Passport\Client as OClient;
use GuzzleHttp\Exception\ClientException;
use App\Repositories\User\UserRepositoryInterface;
class UserRepository implements UserRepositoryInterface {
    const SUCCUSUS_STATUS_CODE = 200;
    const UNAUTHORISED_STATUS_CODE = 401;
    const BASE_URL = "http://mylemp-nginx";
    public function __construct(Client $client) {
        $this->http = $client;
    }
    public function register(Request $request) {
        $email = $request->email;
        $password = $request->password;
        $input = $request->all();
        $input[&#39;password&#39;] = bcrypt($input[&#39;password&#39;]);
        User::create($input);
        $response = $this->getTokenAndRefreshToken($email, $password);
        return $this->response($response["data"], $response["statusCode"]);
    }
    public function login(Request $request) {
        $email = $request->email;
        $password = $request->password;
        if (Auth::attempt([&#39;email&#39; => $email, &#39;password&#39; => $password])) {
            $response = $this->getTokenAndRefreshToken($email, $password);
            $data = $response["data"];
            $statusCode =  $response["statusCode"];
        } else {
            $data = [&#39;error&#39;=>&#39;Unauthorised&#39;];
            $statusCode =  self::UNAUTHORISED_STATUS_CODE;
        }
        return $this->response($data, $statusCode);
    }
    public function refreshToken(Request $request) {
        if (is_null($request->header(&#39;Refreshtoken&#39;))) {
            return $this->response([&#39;error&#39;=>&#39;Unauthorised&#39;], self::UNAUTHORISED_STATUS_CODE);
        }
        $refresh_token = $request->header(&#39;Refreshtoken&#39;);
        $Oclient = $this->getOClient();
        $formParams = [ &#39;grant_type&#39; => &#39;refresh_token&#39;,
                        &#39;refresh_token&#39; => $refresh_token,
                        &#39;client_id&#39; => $Oclient->id,
                        &#39;client_secret&#39; => $Oclient->secret,
                        &#39;scope&#39; => &#39;*&#39;];
        return $this->sendRequest("/oauth/token", $formParams);
    }
    public function details() {
        $user = Auth::user();
        return $this->response($user, self::SUCCUSUS_STATUS_CODE);
    }
    public function logout(Request $request) {
        $request->user()->token()->revoke();
        return $this->response([&#39;message&#39; => &#39;Successfully logged out&#39;], self::SUCCUSUS_STATUS_CODE);
    }
    public function response($data, int $statusCode) {
        $response = ["data"=>$data, "statusCode"=>$statusCode];
        return $response;
    }
    public function getTokenAndRefreshToken(string $email, string $password) {
        $Oclient = $this->getOClient();
        $formParams = [ &#39;grant_type&#39; => &#39;password&#39;,
                        &#39;client_id&#39; => $Oclient->id,
                        &#39;client_secret&#39; => $Oclient->secret,
                        &#39;username&#39; => $email,
                        &#39;password&#39; => $password,
                        &#39;scope&#39; => &#39;*&#39;];
        return $this->sendRequest("/oauth/token", $formParams);
    }
    public function sendRequest(string $route, array $formParams) {
        try {
            $url = self::BASE_URL.$route;
            $response = $this->http->request(&#39;POST&#39;, $url, [&#39;form_params&#39; => $formParams]);
            $statusCode = self::SUCCUSUS_STATUS_CODE;
            $data = json_decode((string) $response->getBody(), true);
        } catch (ClientException $e) {
            echo $e->getMessage();
            $statusCode = $e->getCode();
            $data = [&#39;error&#39;=>&#39;OAuth client error&#39;];
        }
        return ["data" => $data, "statusCode"=>$statusCode];
    }
    public function getOClient() {
        return OClient::where(&#39;password_client&#39;, 1)->first();
    }
}
登入後複製

第六步

#app/Http/Requests/UserLoginRequest.php

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class UserLoginRequest extends FormRequest {
    const UNPROCESSABLE_ENTITY = 422;
    public function rules() {
        return [
            &#39;email&#39; => &#39;required|email&#39;,
            &#39;password&#39; => &#39;required&#39;,
          ];
    }
    protected function failedValidation(Validator $validator) {
        throw new HttpResponseException(response()->json($validator->errors(), self::UNPROCESSABLE_ENTITY));
    }
}
登入後複製

2步驟

app/Http/Requests/UserRegisterRequest.php###
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class UserRegisterRequest extends FormRequest {
    const UNPROCESSABLE_ENTITY = 422;
    public function rules() {
        return [
            &#39;name&#39; => &#39;required&#39;,
            &#39;email&#39; => &#39;required|email|unique:users&#39;,
            &#39;password&#39; => &#39;required&#39;,
            &#39;c_password&#39; => &#39;required|same:password&#39;,
          ];
    }
    protected function failedValidation(Validator $validator) {
        throw new HttpResponseException(response()->json($validator->errors(), self::UNPROCESSABLE_ENTITY));
    }
}
登入後複製
######第八步#########app/Providers/AppServiceProvider.php###
<?php
namespace App\Providers;
use App\Repositories\User\UserRepository;
use App\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register() {
        $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot() {
        //
    }
}
登入後複製
######第九步#########app/Providers/AuthServiceProvider.php###
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider {
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // &#39;App\Model&#39; => &#39;App\Policies\ModelPolicy&#39;,
    ];
    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot() {
        $this->registerPolicies();
        Passport::routes();
    }
}
登入後複製
######第十步#########app/Http /Controllers/UserController.php###
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UserLoginRequest;
use App\Http\Requests\UserRegisterRequest;
use App\Repositories\User\UserRepositoryInterface;
class UserController extends Controller {
    const SUCCUSUS_STATUS_CODE = 200;
    const UNAUTHORISED_STATUS_CODE = 401;
    public function __construct(UserRepositoryInterface $userRepository) {
        $this->userRepository = $userRepository;
    }
    public function login(UserLoginRequest $request) {
        $response = $this->userRepository->login($request);
        return response()->json($response["data"], $response["statusCode"]);
    }
    public function register(UserRegisterRequest $request) {
        $response = $this->userRepository->register($request);
        return response()->json($response["data"], $response["statusCode"]);
    }
    public function details() {
        $response = $this->userRepository->details();
        return response()->json($response["data"], $response["statusCode"]);
    }
    public function logout(Request $request) {
        $response = $this->userRepository->logout($request);
        return response()->json($response["data"], $response["statusCode"]);
    }
    public function refreshToken(Request $request) {
        $response = $this->userRepository->refreshToken($request);
        return response()->json($response["data"], $response["statusCode"]);
    }
}
登入後複製
######第十一步#########routes/api.php###
<?php
use Illuminate\Support\Facades\Route;
Route::post(&#39;login&#39;, &#39;UserController@login&#39;);
Route::post(&#39;register&#39;, &#39;UserController@register&#39;);
Route::post(&#39;refreshtoken&#39;, &#39;UserController@refreshToken&#39;);
Route::group([&#39;middleware&#39; => [&#39;auth:api&#39;]], function () {
    Route::post(&#39;logout&#39;, &#39;UserController@logout&#39;);
    Route::post(&#39;details&#39;, &#39;UserController@details&#39;);
});
登入後複製
###推薦教學:《###Laravel教程###》###

以上是Laravel Passport 建置 API 驗證和授權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:learnku.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板