>PHP 프레임워크 >Laravel >Laravel Passport는 API 인증 및 승인을 구축합니다.

Laravel Passport는 API 인증 및 승인을 구축합니다.

Guanhui
Guanhui앞으로
2020-06-10 09:30:373115검색

Laravel Passport는 API 인증 및 승인을 구축합니다.

1단계

다음 명령을 실행합니다.

composer require laravel/passport
php artisan migrate
php artisan passport:install

2단계

config/auth.php 파일에서 Gurd를 수정합니다.

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

3단계

앱/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;,
    ];
}

4단계

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();
}

5단계

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();
    }
}

6단계

앱/ 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));
    }
}

7단계

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));
    }
}

8단계

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() {
        //
    }
}

9단계

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();
    }
}

Step Ten

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"]);
    }
}

Step Eleven

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 Tutorial "

위 내용은 Laravel Passport는 API 인증 및 승인을 구축합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 learnku.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제