In our previous Angular JWT authentication tutorial, we did the initial setup for angular. It is time to setup backend for login and user authorization using tymon/jwt-auth package in laravel.
You can also use spring boot for any other framework as backend. Since laravel is very easy to configure in the case of CORS and JWT, I am going to use it throughout this tutorial.
However, you can follow skip this step and directly move to the next step if you have other backend services to help you generate and validate login. So, let’s get going.
First, you have to configure CORS Policy. If you are using Laravel 7 then, they automatically have CORS configured. But if you are using the lower versions then, you can check how to setup cors in the laravel tutorial.
Laravel has a package to set up JWT Tymon designs. They have clean and proper documentation of how to implement JWT on laravel. I am also going to follow those simple steps in the documentation. However, I will try to be as simple as possible so, that you can follow along with my tutorial.
Installing TYMON JWT Laravel Package
To Install the JWT package by Tymon, either install via composer typing composer require tymon/jwt-auth
in your terminal. It will install the latest stable version of it.
However, if you want to latest development release you can add the "tymon/jwt-auth": "^1.0.1"
directly in your composer.json
under the “require” section like below. After updating directly in composer.json
do composerĀ dump-autoload
on terminal.
1 2 3 4 5 6 7 8 9 |
"require": { "php": "^7.2.5", "fideloper/proxy": "^4.2", "fruitcake/laravel-cors": "^2.0", "guzzlehttp/guzzle": "^6.3", "laravel/framework": "^7.24", "laravel/tinker": "^2.0", "tymon/jwt-auth": "^1.0.1" }, |
The latest version of laravel automatically adds new packages to providers. However in any case, If you don’t find this line inside config/app.php
in the provider’s section, you can just include the lines below.
1 2 3 |
'providers' => [ Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ] |
After this, you have to publish the package. Enter this in your terminal.
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
After this, you will find jwt.php
inside the config folder.
Finally, it is time to generate the jwt secret key which will be used to sign your tokens.
Type php artisan jwt:secret
in your terminal. It will generate JWT secret key inside your .env
file.
Also, make sure to add least add one user to theĀ database to work with. You can use laravel model factories for it to generate 50 users in bulk.
Next Step
Now, we have to implement JWTSubject interface in User model so that we can use the package features. So update your user model.
We have to implement two methods getJWTIdentifier()
and getJWTCustomClaims()
. You can copy this whole User model and paste unless you have changed anything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php namespace App; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { use Notifiable; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; protected $casts = [ 'email_verified_at' => 'datetime', ]; public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; } } |
Configure Auth Guards
We need our guards to use jwt authentication. So, we have to make some changes into config/auth.php
. So open up and change your default guards from web
to api
.
1 2 3 4 |
'defaults' => [ 'guard' => 'api', // change from web ---> api 'passwords' => 'users', ], |
Also, change guards in the API section from token
to jwt
.
1 2 3 4 5 6 7 8 9 10 11 12 |
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', // change from token ---> jwt 'provider' => 'users', 'hash' => false, ], ], |
Finally, time to configure routes. Copy these lines inside your routes/api.php
As suggested in the JWT documentation we can create a separate controller or use it inside any controller. But I would like to create one since it makes my codes cleaner to split codes into multiple files.
Enter php artisan make:controller AuthController
in the terminal to generate the controller file and copy these lines below inside it.
1 2 3 4 5 6 |
Route::group(['middleware' => 'api', 'prefix' => 'auth'], function () { Route::post('login', 'AuthController@login'); Route::post('logout', 'AuthController@logout'); Route::post('refresh', 'AuthController@refresh'); Route::post('me', 'AuthController@me'); }); |
Now you can try visiting these API by providing valid credentials to check if it works or not. If it doesn’t work then, you might have missed some steps.
If you have any problem till now, contact me via the contact form, so that I could help you. Finally, In the next article, we are going to sync Angular & laravel and validate login. Make sure not to miss any of these steps.
Finally, its time to do validating login in angular. Since this is all about validating login in Laravel side I am going to write another post handling validation in angular in this link.
Leave a Reply