Home > PHP Framework > Laravel > body text

Laravel Passport builds API authentication and authorization

Guanhui
Release: 2020-06-10 09:30:37
forward
3075 people have browsed it

Laravel Passport builds API authentication and authorization

First step

Execute the following command:

composer require laravel/passport
php artisan migrate
php artisan passport:install
Copy after login

Second step

Modify Gurds in the config/auth.php file:

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

Step 3

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;,
    ];
}
Copy after login

Step 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();
}
Copy after login

Step 5

Create app/Repositories/User /UserRepository.php file

<?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();
    }
}
Copy after login

Step Six

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));
    }
}
Copy after login

Step Seven

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));
    }
}
Copy after login

Step 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() {
        //
    }
}
Copy after login

Step 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();
    }
}
Copy after login

Step 10

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

Step 11

##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;);
});
Copy after login
Recommended tutorial: "

Laravel Tutorial

The above is the detailed content of Laravel Passport builds API authentication and authorization. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!