How to Authenticate user in NodeJS with socket io using JWT in Laravel 8?

NodeJS with socket io using JWT in Laravel 8

Today now in this post i want to show you How to Authenticate user in NodeJS with socket io using JWT in Laravel 8? Here i am going to teach you about how we can authenticate user node js by using JWT and socket io in Laravel application. You have to know that it is very very important. Because if you have to working on any chat application or any messengers system etc with user. Then you must need to use JWT token because it is a very safe and also secure way.

If you are work on chat any module with socket io then someone can easily hack our applicaation. So at that time you have to check given JWT token is valid or not by using socketio-jwt package of Node.

By using socketio-jwt package you can simply check authentication with user. And also identify that token is valid or not, and also you can get information of login user from the JWT token. As like user_id, name, email etc as we need.

But if you thinking how you can do this with your Laravel application. So, here just you have to just follow bellow step because it from the scratch.

Step 1: Install Laravel Application

In the first step, if you haven’t any laravel application setup then you can need a fresh laravel application. Now run the bellow command. Then you get clean fresh laravel application.

composer create-project --prefer-dist laravel/laravel blog

Ok, now open your Laravel application root directory and run the bellow command. By using this commands we can make auth and create migration table.

php artisan make:auth
php artisan migrate
Step 2: JWT Package Installation

Have to know JWT stand for Json Web Token. JWT will helps you to make authentication and connect with front-end and back-end function. By using JWT you can create a login and register API. So at first we need to install “tymon/jwt-auth” package in laravel .

We are also need to installing barryvdh/laravel-cors. This package will handle Cross-Origin Resource Sharing (CORS).

So, run the bellow command and install.

composer require barryvdh/laravel-cors tymon/jwt-auth

After the successfully install this package. You need open config/app.php file and add this service provider.

config/app.php

'providers' => [
	....
	Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
	Barryvdh\Cors\ServiceProvider::class,
]
....

After this you have to publish the configuration by using following command:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Ok now, we need to add the CORS middleware to the location `app/Http/Kernel.php` global as like as bellow:

app/Http/Kernel.php

....
protected $middlewareGroups = [
        'web' => [
            .......
            \Barryvdh\Cors\HandleCors::class,
        ],
        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
....

Now you have to make more secure JWT token by using JWT Secret. So you can set the JWT secret on your ‘.env’ file. Now open env file and put bellow line:

.env

JWT_SECRET=B1Bbr8EnAdJASz3l7Wl0U69f4UHsdtDX
Step 3: Create Token Route

In this is step you have to create a route of generate JWT token. So need to open your routes/web.php file and add the following route.

Route::get('token', 'TokenController@token');
Step 4: Create Controller

So in this step, now you should create a new controller as name TokenController. In this path app/Http/Controllers/TokenController.php . By using bellow command.

php artisan make:controller TokenController

So this controller will return us a token. Now put the bellow content in controller file:

app/Http/Controllers/TokenController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

class TokenController extends Controller
{

    public function token(Request $request, \Tymon\JWTAuth\JWTAuth $auth)
    {
    	Auth::loginUsingId($request->id);


        $user = Auth::user();
        $claims = ['userid' => $user->id, 'email' => $user->email];


        $token = $auth->fromUser($user, $claims);
        return response()->json(['token' => $token]);
    }
}
Step 5: Install Node JS

In this step you have to install nodejs. If you haven’t installed before. So, at first make sure. You can check if nodejs is not install in your system. Then you can install by fire following command easily.

sudo apt-get update
sudo apt-get install nodejs
Step 6: Install npm

Now you have also need to install npm because you need to install more socket.io, socketio-jwt and express package by using npm command. So if you not installed before, then using this command you can install.

sudo apt-get install npm
Step 7: Install NodeJS Other Packages

Now in this step you have to install the several package as like as bellow:

  1. Express
  2. Socket.io
  3. Dotenv
  4. Socketio-jwt

Need to run bellow command for install above nodejs packages:

npm install express socket.io socketio-jwt dotenv --save
Step 8: NodeJS File

Now you need to create the nodejs file. So at first go on your laravel root directory and then create nodejs. And inside that folder need to create server.js File. Then put the bellow code on that file:

nodejs/server.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var socketioJwt = require('socketio-jwt');
var myEnv = require('dotenv').config({path:'../.env'});


/* 
Accept connection and authorize token code
*/
io.on('connection', socketioJwt.authorize({
    secret: myEnv.JWT_SECRET,
    timeout: 15000
}));


/* 
When authenticated, send back userid + email over socket
*/
io.on('authenticated', function (socket) {


    console.log(socket.decoded_token);
    socket.emit('user-id', socket.decoded_token.userid);
    socket.emit('user-email', socket.decoded_token.email);


    socket.on('public-my-message', function (data) {
		socket.emit('receive-my-message', data.msg);
    });


});


/* 
Start NodeJS server at port 3000
*/
server.listen(3000);
Step 9: JS File

That’s good now you are in last step of our this tutorial. Now in this step you have to create a file as  Userauth.html file. Now in this file you have to write all code for fire Ajax. And also get token from the Laravel application. Then send token on the nodejs server.

So, put all bellow code on that file:

Userauth.html

<!doctype html>
<html lang="en">
<head>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.js"></script>
</head>
<body>


<h1>Socket Connection Status: <span id="connection"></span></h1>
<h1>Login User Id: <span id="userid"></span></h1>
<h1>Login User Email: <span id="email"></span></h1>
<h1>Public Message: <span id="receive-my-message"></span></h1>


<script type="text/javascript">
    $(document).ready(function () {
        socketIOConnectionUpdate('Requesting JWT Token from Laravel');


        $.ajax({
            url: 'http://localhost:8000/token?id=1'
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            socketIOConnectionUpdate('Something is wrong on ajax: ' + textStatus);
        })
        .done(function (result, textStatus, jqXHR) {


            /* 
            make connection with localhost 3000
            */
            var socket = io.connect('http://localhost:3000');


            /* 
            connect with socket io
            */
            socket.on('connect', function () {
                socketIOConnectionUpdate('Connected to SocketIO, Authenticating')
                socket.emit('authenticate', {token: result.token});


                socket.emit('public-my-message', {'msg': 'Hi, Every One.'});
            });


            /* 
            If token authenticated successfully then here will get message 
            */
            socket.on('authenticated', function () {
                socketIOConnectionUpdate('Authenticated');
            });


            /* 
            If token unauthorized then here will get message 
            */
            socket.on('unauthorized', function (data) {
                socketIOConnectionUpdate('Unauthorized, error msg: ' + data.message);
            });


            /* 
            If disconnect socketio then here will get message 
            */
            socket.on('disconnect', function () {
                socketIOConnectionUpdate('Disconnected');
            });


            /* 
            Get Userid by server side emit
            */
            socket.on('user-id', function (data) {
                $('#userid').html(data);
            });


            /* 
            Get Email by server side emit
            */
            socket.on('user-email', function (data) {
                $('#email').html(data);
            });


            /* 
            Get receive my message by server side emit
            */
            socket.on('receive-my-message', function (data) {
                $('#receive-my-message').html(data);
            });
        });
    });


    /* 
    Function for print connection message
    */
    function socketIOConnectionUpdate(str) {
        $('#connection').html(str);
    }
</script>
</body>
</html>

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.