---
description: >-
  https://medium.com/modulr/create-api-authentication-with-passport-of-laravel-5-6-1dc2d400a7f
---

# Create API Rest with Laravel 5.6 Passport Authentication (Part 1)

## Create API Rest with Laravel 5.6 Passport Authentication (Part 1) <a href="#c99e" id="c99e"></a>

[![Alfredo Barron](https://miro.medium.com/fit/c/96/96/1*_RpT5iWcS972YjR9jl30rA.jpeg)](https://medium.com/@alfredobarron?source=post_page-----1dc2d400a7f----------------------)[Alfredo Barron](https://medium.com/@alfredobarron?source=post_page-----1dc2d400a7f----------------------)Follow[May 9, 2018](https://medium.com/modulr/create-api-authentication-with-passport-of-laravel-5-6-1dc2d400a7f?source=post_page-----1dc2d400a7f----------------------) · 5 min read

We learning to create a authentication system with API Laravel Authentication Passport OAuth

Notice we recommend upgrading to a more modern version. [Read upgrade instructions](https://medium.com/modulr/create-api-rest-with-laravel-7-passport-authentication-part-1-a8198e5d0a9?source=friends_link\&sk=553126f69becb76a9ed98c8c930eefe9).![Image for post](https://miro.medium.com/max/60/1*PGjkVizr0qb5cOYYfmkLbA.jpeg?q=20)![Image for post](https://miro.medium.com/max/1920/1*PGjkVizr0qb5cOYYfmkLbA.jpeg)

## Step 1. Install Laravel <a href="#id-0f66" id="id-0f66"></a>

In first step, we require to get fresh Laravel application using bellow command, So open your terminal or command prompt and run bellow command:

```
laravel new auth
```

## Step 2. Install Laravel Passport Package <a href="#id-2f41" id="id-2f41"></a>

Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.

```
composer require laravel/passport
```

## Step 3. Run Migration <a href="#c79f" id="c79f"></a>

The Passport migrations will create the tables your application needs to store clients and access tokens.

```
php artisan migrate
```

## Step 4. Generate keys <a href="#id-9586" id="id-9586"></a>

This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “_personal access_” and “_password grant_” clients which will be used to generate access tokens:

```
php artisan passport:install
```

After running this command, add the `Laravel\Passport\HasApiTokens` trait to your `App\User`model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:

## Step 5. Passport Config <a href="#id-48a4" id="id-48a4"></a>

```
<?phpnamespace App;use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;class User extends Authenticatable
{
    use Notifiable, HasApiTokens;
}
```

Next, you should call the `Passport::routes` method within the `boot` method of your `AuthServiceProvider`. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

```
<?phpnamespace App\Providers;use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();        Passport::routes();
    }
}
```

Finally, in your `config/auth.php` configuration file, you should set the `driver` option of the `api` authentication guard to `passport`. This will instruct your application to use Passport's `TokenGuard` when authenticating incoming API requests:

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

## Step 6. Create API Routes <a href="#b95b" id="b95b"></a>

We will create api routes. Laravel provide `routes/api.php` file for write web services route. So, let’s add new route on that file.

```
<?phpuse Illuminate\Http\Request;Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');
  
    Route::group([
      'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'AuthController@logout');
        Route::get('user', 'AuthController@user');
    });
});
```

## **Step 7: Create Controller** <a href="#id-9cb9" id="id-9cb9"></a>

In last step we have to create new controller and four api method. So let’s create `AuthController` and put bellow code:

```
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;class AuthController extends Controller
{
    /**
     * Create user
     *
     * @param  [string] name
     * @param  [string] email
     * @param  [string] password
     * @param  [string] password_confirmation
     * @return [string] message
     */
    public function signup(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed'
        ]);        $user = new User([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);        $user->save();        return response()->json([
            'message' => 'Successfully created user!'
        ], 201);
    }
  
    /**
     * Login user and create token
     *
     * @param  [string] email
     * @param  [string] password
     * @param  [boolean] remember_me
     * @return [string] access_token
     * @return [string] token_type
     * @return [string] expires_at
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);        $credentials = request(['email', 'password']);        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);        $user = $request->user();        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);        $token->save();        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }
  
    /**
     * Logout user (Revoke the token)
     *
     * @return [string] message
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }
  
    /**
     * Get the authenticated User
     *
     * @return [json] user object
     */
    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}
```

> Now we are ready to run our example so run bellow command to quick run:

```
php artisan serve
```

## Tests <a href="#a30c" id="a30c"></a>

Now, we can simple test by rest client tools (Postman), So I test it and you can see below screenshots.

> In this api you have to set two header as listed below:

```
Content-Type: application/json
X-Requested-With: XMLHttpRequest
```

![Image for post](https://miro.medium.com/max/1015/1*L_0N9wW3rS2plp4gYm9SLA.jpeg)

Signup

![Image for post](https://miro.medium.com/max/60/1*thPhuhyi05AJhb8lxwfChg.png?q=20)

![Image for post](https://miro.medium.com/max/1019/1*thPhuhyi05AJhb8lxwfChg.png)

Login

![Image for post](https://miro.medium.com/max/60/1*8x2u4vfwRVuR1rATYpn7Eg.png?q=20)

![Image for post](https://miro.medium.com/max/1018/1*8x2u4vfwRVuR1rATYpn7Eg.png)

Logout

![Image for post](https://miro.medium.com/max/60/1*swCTkLj840Dywb5o3SKUFQ.png?q=20)

![Image for post](https://miro.medium.com/max/1018/1*swCTkLj840Dywb5o3SKUFQ.png)

User

![Image for post](https://miro.medium.com/max/60/1*VJjrHFpkyA-z3o0TrIG4dw.png?q=20)

![Image for post](https://miro.medium.com/max/1018/1*VJjrHFpkyA-z3o0TrIG4dw.png)

> Thanks for reading! I’m Alfredo Barrón, Feel free to connect with me via [Twitter](https://twitter.com/AlfredoBarronC).

**Part 1. Passport Authentication**\
Part 2. [Confirm account + notifications](https://medium.com/modulr/create-api-authentication-passport-in-laravel-5-6-confirm-account-notifications-part-2-5e221b021f07)\
Part 3. [Generate avatar](https://medium.com/modulr/api-rest-with-laravel-5-6-passport-authentication-generate-avatar-part-3-d92ec7935eff)\
Part 4. [Reset Password](https://medium.com/modulr/api-rest-with-laravel-5-6-passport-authentication-reset-password-part-4-50d27455dcca)\
Part 5. [Send Notifications with Queues on Redis](https://medium.com/modulr/api-rest-with-laravel-5-6-175eea5db3e8)

### Resources <a href="#id-5231" id="id-5231"></a>

[-GitHub](https://github.com/modulr/api-laravel-passport)\
-[Postman collections](https://documenter.getpostman.com/view/1657780/RW1ejGzL)

### References <a href="#id-2f9d" id="id-2f9d"></a>

[-Laravel Passport](https://laravel.com/docs/5.6/passport)\
-[Create REST API in Laravel with authentication using Passport](https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876) _excelent tutorial by_ [Urjit Rajgor](https://medium.com/u/76d4e8685b04?source=post_page-----1dc2d400a7f----------------------)
