Home > Backend Development > PHP Tutorial > How to use laravel Passport to implement API authentication

How to use laravel Passport to implement API authentication

不言
Release: 2023-04-03 08:22:01
Original
2136 people have browsed it

This article mainly introduces how to use laravel Passport for API authentication. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Install larave

laravel new passport_demo
cd passport_demo && composer install
Copy after login

Modify the database configuration in .env to your own database configuration

 DB_DATABASE=homestead
 DB_USERNAME=homestead
 DB_PASSWORD=secret
Copy after login

Installing Passport

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

The following errors may occur during execution

Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
Copy after login

Edit

 namespace App\Providers;
 use Illuminate\Support\ServiceProvider;
 use Illuminate\Support\Facades\Schema;//新增
 class AppServiceProvider extends ServiceProvider{
     public function boot(){}
     public function register(){
         Schema::defaultStringLength(191);//新增
     }
 }
Copy after login

Then execute these two commands again

php artisan migrate
php artisan passport:install
Copy after login

Edit to add to

 namespace App;
 use Illuminate\Notifications\Notifiable;
 use Illuminate\Foundation\Auth\User as Authenticatable;
 use Laravel\Passport\HasApiTokens;//新增
 class User extends Authenticatable{
     use Notifiable;
     use HasApiTokens;//新增
     protected $fillable = ['name', 'email', 'password',];
     protected $hidden = ['password', 'remember_token',];
 }
Copy after login

Call the function in the method

 namespace App\Providers;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
 use Laravel\Passport\Passport;//新增
 class AuthServiceProvider extends ServiceProvider{
     protected $policies = ['App\Model' => 'App\Policies\ModelPolicy',];
     public function boot(){
         $this->registerPolicies();
         Passport::routes();//新增
     }
 }
Copy after login

Add the options of the authorization guard in the configuration file Create the file instead

//修改前
 'guards' => [
     'web' => [
         'driver' => 'session',
         'provider' => 'users',
     ],
     'api' => [
         'driver' => 'token',
         'provider' => 'users',
     ],
 ],
Copy after login
// 修改后
 'guards' => [
     'web' => [
         'driver' => 'session',
         'provider' => 'users',
     ],
     'api' => [
         'driver' => 'passport',
         'provider' => 'users',
     ],
 ],
Copy after login

, the code here is from another tutorial.

 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use App\Http\Controllers\Controller;
 use App\User;
 use Illuminate\Support\Facades\Auth;
 use Validator;
 class UserController extends Controller {
     public $successStatus = 200;
     public function login() {
         if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
             $user = Auth::user();
             $success['token'] =  $user->createToken('MyApp')->accessToken;
             return response()->json(['success' => $success], $this->successStatus);
         }
         else{
             return response()->json(['error'=>'Unauthorised'], 401);
         }
     }
     public function register(Request $request) {
         $validator = Validator::make($request->all(), [
             'name' => 'required',
             'email' => 'required|email',
             'password' => 'required',
             'c_password' => 'required|same:password',
         ]);
         if ($validator->fails()) {
             return response()->json(['error'=>$validator->errors()], 401);
         }
         $input = $request->all();
         $input['password'] = bcrypt($input['password']);
         $user = User::create($input);
         $success['token'] =  $user->createToken('MyApp')->accessToken;
         $success['name'] =  $user->name;
         return response()->json(['success'=>$success], $this->successStatus);
     }
     public function details() {
         $user = Auth::user();
         return response()->json(['success' => $user], $this->successStatus);
     }
 }
Copy after login

Use postman to test
Registration interface, after successful registration, the token and user name will be returned
How to use laravel Passport to implement API authentication

Login interface
How to use laravel Passport to implement API authentication

Details interface
How to use laravel Passport to implement API authentication

Related recommendations:

About the installation and configuration process of Laravel October

The above is the detailed content of How to use laravel Passport to implement API authentication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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