Laravel Echo & Laravel-Echo-Server API Authentication using Passport

João Marques
Aug 2, 2018 · 2 min read

A guide to use Passport API authentication using Laravel Echo and Laravel-echo-server in multi-platform JavaScript Applications.


With the rise in popularity of multi-platform JavaScript applications, such as React with React Native, comes the necessity to build server-side systems capable of handling these applications.

In this post we’ll go over the Laravel-echo-server socket system, and how to configure it to use a different method of authentication, in this case using Passport OAuth2.

If you want to learn how to configure Laravel-echo-server first, be sure to check Adnan’s tutorial.

Laravel-Echo-Server default authentication

After running LES init command

$ laravel-echo-server init

A Json configuration file is generated the default authentication, using Laravel’s broadcasting authentication system.

laravel-echo-server.json
...
"authEndpoint": "/broadcasting/auth",....

This endpoint is set to use the default Laravel authentication, which you probably noticed by now . We’ll have to alter a few things to get this working with Passport.

Broadcast Service Provider

In your Broadcast service provider, you can find the declaration of your broadcast routes…

App/Porviders/BroadcastServiceProvider.php...
public function boot()
{Broadcast::routes();

Change it to use Passport’s middleware. This way, instead of using Laravel’s authentication middleware, the authentication request will instead use Passport’s authentication system.

Broadcast::routes(["prefix" => "api", "middleware" => "auth:api"]);

Laravel echo server

As stated before, your LES configuration file looks like this…

laravel-echo-server.json
...
"authEndpoint": "/broadcasting/auth",....

Since we added /api prefix, we need to change this parameter…

laravel-echo-server.json
...
"authEndpoint": "/api/broadcasting/auth",....

Laravel Echo

By now, your instance of Laravel Echo looks something like this…

window.Echo = new Echo({broadcaster: "socket.io",host: window.location.hostname + ":8080" });

In order to use Passport’s authentication, we need to attach the authentication bearer token to the request header….

window.Echo = new Echo({broadcaster: "socket.io",host: window.location.hostname + ":8080",auth: {headers: {Authorization: "Bearer " + bearerToken}}});

You’re all set!

After those changes, Laravel-echo-server should start using Passport OAuth2 to authenticate your socket connections!

Follow Me

Linked In

João Marques

Written by

Software Engineer @ xgeeks

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade