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
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
The Passport migrations will create the tables your application needs to store clients and access tokens.
php artisan migrate
Step 4. Generate keys
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:
After running this command, add the Laravel\Passport\HasApiTokens trait to your App\Usermodel. 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
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:
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:
Step 6. Create API Routes
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.
Step 7: Create Controller
In last step we have to create new controller and four api method. So let’s create AuthController and put bellow code:
Now we are ready to run our example so run bellow command to quick run:
Tests
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:
Image for post
Signup
Image for post
Image for post
Login
Image for post
Image for post
Logout
Image for post
Image for post
User
Image for post
Image for post
Thanks for reading! I’m Alfredo Barrón, Feel free to connect with me via Twitter.
<?phpnamespace App;use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;class User extends Authenticatable
{
use Notifiable, HasApiTokens;
}
<?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();
}
}