CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Laravel   Laravel 7 JWT Authentication Using Tymon/JWT-Auth

Laravel 7 JWT Authentication Using Tymon/JWT-Auth

September 18, 2020 by SNK

Laravel 7 JWT Authentication Using Tymon/JWT-Auth

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.

composer.json
JavaScript
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.

config/app.php
PHP
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.

User.php
PHP
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.

config/auth.php
PHP
1
2
3
4
'defaults' => [
        'guard' => 'api', // change from web ---> api
        'passwords' => 'users',
    ],

Also, change guards in the API section from token to jwt.

config/auth.php
PHP
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.

routes/api.php
PHP
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.

SHARE ON
Buffer

Enjoyed this article?

Like us on

Laravel

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.