Realtime chat client authentication with Laravel Passport, SocketIO, Laravel Echo

Tram Ho

Hello, it’s me again

These days, the epidemic in Vietnam is so stressful, I don’t know when I will be able to return to my motherland. Remember to take care of your health so that you can stay healthy and code

In previous posts in this chat application writing series, I used session to authenticate the user’s account along with authentication for laravel echo. But in real projects, authentication via JWT Token is also very popular. Quite a few of you have asked me about this.

Today, I take advantage of my free time to write this article so that from now on you have something to watch directly and follow along without having to search google anymore.

The article will be quite short, not wordy like other articles, so you can rest assured

Setup

First of all, please help me clone the source code for this post here Please.

After the clone is complete, run the following commands in turn to install the libraries and some related settings:

You update the database connection information in .env to match your environment, then continue to run the following commands:

Finally, let’s try to run the app:

Finally, you open the browser at the address http://localhost:8000/chat, Click Register to register a new account, after successful registration you will be taken to the main screen as follows:

Please try to type a few messages and send to see if everything is ok, try F5 again in the browser to make sure the old messages are saved in the database.

Project overview:

  • In this project I use Laravel Passport for authentication (login, register, send/load message). I use JWT Token to authenticate all APIs
  • The routes for Laravel I declare in routes/api.php, the frontend uses Vue Router
  • I follow all the setup steps for Laravel Passport Laravel’s docs, nothing magical here

Let’s go to the main part of today

Realtime

The mandatory condition for this article is that you must have Redis running on your computer, on windows installing Redis will be a bit more banana, so I encourage you to use Docker to run Redis (1 note is up)

First we install predis for the Laravel side:

Then in .env You update the broadcast configuration for Laravel as follows:

Next, open the file config/database.php find item redis and edit it a bit client and options as follows:

Then open the file config/app.php, find item providers Please uncomment the following line:

Next we set up Laravel Echo Server. If you do not have Laravel Echo Server installed on your device, you should run it npm install -g laravel-echo-server first

You give yourself the following command:

Please choose from the following options:

Next we open the file laravel-echo-server.json and update in authEndpoint add prefix /api (for this post we use all routes /api but):

Then we need to install Laravel Echo for the frontend (VueJS):

Please update the file again resources/views/layouts/app.blade.php add paragraph header right after js/app.js give me the following:

Let’s run Laravel Echo Server, let’s run it:

Remember to make sure that the laravel echo server is running fine guys

Next we open the file resources/js/app.js Let’s update a little bit like this:

As you can see the difference of this article compared to the previous ones is that we only initiate the connection to the Laravel echo server after we get the information of the current login user, the purpose is to ensure that the user is authenticated. , and the important part is that we pass the token into the field auth to authenticate with the Laravel echo server side:

Then we go back to the browser and press F5 to make sure everything is ok, check the Network to make sure nothing is wrong:

Next we open the file resources/js/components/Chat.vue live created We add the following:

As you can see above, we will let the user join the private channel named chatroom and listen to events MessagePosted If you see a new message, print it to the console.

You save and we go back to the browser press F5 and notice the terminal where Laravel Echo Server is running, we will see the error printed as follows:

The error printed here is because when we join the channel chatroom then Laravel Echo Server it needs to authenticate with the Laravel side, and since we are setting authEndpoint (in laravel-echo-server.json) is /api/broadcasting/auth, but that route we have never declared it anywhere, so it gives an error not found.

Now let’s open the file routes/api.php and declare for that route:

Okay, now we go back to the browser and press F5 again and look at the terminal where Laravel Echo Server is running, you will see the following:

So we have completed the authentication with Laravel Echo Server with JWT Token already, everything else is the same as in the previous posts.

First we create event MessagePosted (this event will be called every time a message is saved successfully):

Then we open the file app/Events/MessagePosted.php and update some parts as follows:

Finally we open the file routes/api.php To save the message, we add a line like this:

Then we go back to the Chat.vue file and update created and add method scrollToBottom as follows:

Next, remember to run queue:work:

That’s ok, now we go back to the browser and open 2 tabs, log in to 2 different accounts (open an incognito tab), try chat if realtime is a problem then:

Authentication for each channel

If you notice, we don’t need to use files in this article routes/channels.php, currently we are return true; ie for users to join any private channel, but in reality we will often have many channels and for 1 user we only want to let them join a few channels.

From the Laravel Echo Server side, each time it authenticates, it will be attached channel_name and we can rely on that for arbitrary processing:

End

It’s been a long time since there was a “fast train” song like this.

Through this article, you can see that using JWT Token to authenticate with Laravel Echo Server is not too difficult, right? But because I see the documentation and tutorials online mainly use sessions (like I did in previous posts), so when I go to the actual project and use JWT, I’m confused about how to do it, I hope In this article, you have a better understanding of how to use it.

Good luck to you and see you in the next posts

Share the news now