Heim > PHP-Framework > Laravel > Laravel Passport erstellt API-Authentifizierung und -Autorisierung

Laravel Passport erstellt API-Authentifizierung und -Autorisierung

Guanhui
Freigeben: 2020-06-10 09:30:37
nach vorne
3095 Leute haben es durchsucht

Laravel Passport erstellt API-Authentifizierung und -Autorisierung

Schritt 1

Führen Sie den folgenden Befehl aus:

composer require laravel/passport
php artisan migrate
php artisan passport:install
Nach dem Login kopieren

Schritt 2

Gurds in der Datei config/auth.php ändern:

...
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
...
Nach dem Login kopieren

Schritt 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;,
    ];
}
Nach dem Login kopieren

Schritt 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();
}
Nach dem Login kopieren

Schritt 5

App/Repositories/User /UserRepository.php erstellen Datei

<?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();
    }
}
Nach dem Login kopieren

Schritt 6

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));
    }
}
Nach dem Login kopieren

Schritt 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));
    }
}
Nach dem Login kopieren

Schritt 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() {
        //
    }
}
Nach dem Login kopieren

Schritt 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();
    }
}
Nach dem Login kopieren

Schritt 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"]);
    }
}
Nach dem Login kopieren

Schritt 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;);
});
Nach dem Login kopieren

Empfohlenes Tutorial: „Laravel Tutorial

Das obige ist der detaillierte Inhalt vonLaravel Passport erstellt API-Authentifizierung und -Autorisierung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:learnku.com
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage