Hello to all, welcome to therichpost.com. In this post, I will tell you, how to Create Rest Api Authentication in Laravel 5.7 Using Passport Package?
API means Application Programming Interface which transfers data in two applications in Json format. In laravel, we create api’s for our mobile developers or get the data from other applications. APIs use tokens to authenticate users and do not maintain session between requests. In my previous posts, I did laravel api’s for Angular 6, React Js and Vue Js applications.
In this post, I will use Laravel Passport Package to create api auth and here is the full and easy process:
1. Very first, we need to install Laravel 5.7 Passport Package by run below command into your terminal:
composer require laravel/passport
2. After run above command, you need to add below code into your config/app.php file:
'providers' => [ .... Laravel\Passport\PassportServiceProvider::class, .... ],
3. We need to run migration command to add Passport package table in our database:
php artisan migrate
4. After run above command, we will get below error in our terminal:
5. To overcome this error, we need to update our app\Providers\AppServiceProvider file with below code:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(191); } /** * Register any application services. * * @return void */ public function register() { // } }
6. After done the above code, we need to again run the migrate command but first delete the users table from your database, otherwise, we can face again error
:
php artisan migrate
7. After successfully run above command, you can see below tables in your database:
8. Next, we need to install passport with run below command into your terminal:
This will create security token keys:
php artisan passport:install
9. After run above command, we need to update app/User.php file with below code:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; }
10. After, update your app/Providers/AuthServiceProvider.php file with below code:
<?php namespace App\Providers; use Laravel\Passport\Passport; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(191); Passport::routes(); } /** * Register any application services. * * @return void */ public function register() { // } }
11. After it, above your config/auth.php with below code:
return [ ..... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], ..... ]
12. Finally, we need to create our API’S Routes with below code in routes/api.php:
<?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::post('login', 'API\AuthController@login'); Route::post('register', 'API\AuthController@register');
13. We need to create API Folder Into our app\Http\Controllers:
14. In app\Http\Controllers\API Folder, we need to create new file named AuthController.php file and add below code into this file:
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\User; use Validator; class AuthController extends Controller { /** * Login API * * @return \Illuminate\Http\Response */ public function login(Request $request){ if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ $user = Auth::user(); $success['token'] = $user->createToken('LaraPassport')->accessToken; return response()->json([ 'status' => 'success', 'data' => $success ]); } else { return response()->json([ 'status' => 'error', 'data' => 'Unauthorized Access' ]); } } /** * Register API * * @return \Illuminate\Http\Response */ 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()]); } $postArray = $request->all(); $postArray['password'] = bcrypt($postArray['password']); $user = User::create($postArray); $success['token'] = $user->createToken('LaraPassport')->accessToken; $success['name'] = $user->name; return response()->json([ 'status' => 'success', 'data' => $success, ]); } }
15. After all this, we need to test our’s api’s by downloading the postman software:
https://www.getpostman.com/apps
16. Here I tested Register Api by enter name, email, password, and c_password. c_password details:
17. Here, I tested Login Api:
Now, we are done with Rest Api Authentication in Laravel 5.7 Using Passport Package . If you have any query related to this post, then do comment below or ask questions.
Hello,
I’m wondering why don’t you use the routes created by Passport ?
And why do you create security token keys if you don’t use them? If you use the route oauth/token Passport ask you to fill grant_id field and the grant client key, which is the interest to install the security token keys.
Hi Francois, good point.
I will clear in my next post. In this post, I am just giving simple example with tokens.
Hello Ajay Malhotra,
before everything very well contribution.
I have a problem and I have my Api created and I need to consume it from several different domains, example dominio.com and dominio1.com and I get the following error:
Access to XMLHttpRequest at ‘http: //api.grebo.test: 9000 / oauth / token’ from origin ‘http: //grebo.test: 90’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin ‘header is present on the requested resource.
I hope you can help me.
P.S:
Excuse my spelling, is that I do not speak English 🙂
HI, Grebo, thank you for asking:
There, you can check out this package: github.com/barryvdh/laravel-cors.
I personally use it to solve this problem too.
================
or you can try this:
https://therichpost.com/question/angular-6-no-access-control-allow-origin-header-is-present-on-the-requested-resource
hello I’m testing this tutorial the register one it works but the login one shows an error :
{
“status”: “error”,
“data”: “Unauthorized Access”
}
with status: 200 OK
any help please
May be you are using wrong credentials.
how?
I followed step by step this tutorial
You are checking with passport?
yes