Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Laravel Echo returns AuthError in error callback #417

Open
heinergiehl opened this issue Feb 24, 2025 · 1 comment
Open

Laravel Echo returns AuthError in error callback #417

heinergiehl opened this issue Feb 24, 2025 · 1 comment

Comments

@heinergiehl
Copy link

heinergiehl commented Feb 24, 2025

Echo Version

2.0

Laravel Version

12

PHP Version

8.2

NPM Version

10.8.3

Database Driver & Version

No response

Description

I am trying to create a simple Realtime-Online-list. For this, i am trying to join a presence room:

<template>
  <div></div>
</template>

<script lang="ts" setup>
  const { $echo } = useNuxtApp()

  //presence channel test
  onMounted(() => {
    $echo
      .join("test-abc")
      .here((users) => {
        console.log(users)
      })
      .joining((user) => {
        console.log(user)
      })

      .error((error) => {
        console.log(error)
      })
  })
</script>

<style></style>

but the error-callback logs to the console : {type: 'AuthError', error: undefined}
Here more of my Nuxt3 frontend code:

import Echo from "laravel-echo"
import Pusher from "pusher-js"
import type { ChannelAuthorizationCallback } from "pusher-js"
window.Pusher = Pusher
export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig()
  console.log(config.public)
  const echo = new Echo({
    withCredentials: true,
    broadcaster: "reverb",
    key: config.public.REVERB_KEY,
    wsHost: config.public.REVERB_HOST,
    scheme: config.public.REVERB_SCHEME,
    wsPort: 8080,
    host: config.public.REVERB_HOST,

    enabledTransports: ["ws", "wss"],
    encrypted: false,
    forceTLS: false,
    authorizer: (channel: any, options: any) => {
      return {
        authorize: async (
          socketId: string,
          callback: ChannelAuthorizationCallback
        ) => {
          // request xsrf token
          await useFetch("http://localhost:8000/sanctum/csrf-cookie", {
            method: "GET",
            credentials: "include",
          })
          const token = useCookie("XSRF-TOKEN").value || ""
          console.log(token)
          await useFetch("http://localhost:8000/broadcasting/auth", {
            method: "POST",
            credentials: "include",

            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              "X-XSRF-TOKEN": token,
              Authorization: "Bearer " + token,
            },

            body: {
              socket_id: socketId,
              channel_name: channel.name,
            },
          })
            .then((data) => {
              console.log("ALERT123")
              callback(false, data)
            })
            .catch((error) => {
              console.log("ALERT123")
              callback(true, {
                auth: null,
                data: null,
              })
            })
        },
      }
    },
  })

  return {
    provide: {
      echo,
    },
  }
})

On my backend, I am using Laravel 12, but before I tried Laravel 11, and had the the problem. Here the code:

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::routes(['middleware' => ['api', 'auth:sanctum']]);
Broadcast::channel('test-abc', function ($user) {
    Log::info('test-abc', ['user' => $user]);
    return ['id' => $user->id, 'name' => $user->name];
});

bootstrap/app.php:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        api: __DIR__ . '/../routes/api.php',
        commands: __DIR__ . '/../routes/console.php',
        channels: __DIR__ . '/../routes/channels.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->statefulApi();
        $middleware->redirectGuestsTo('login');
    })
    ->withBroadcasting(
        __DIR__ . '/../routes/channels.php',
        ['middleware' => ['auth:sanctum', 'auth:web', 'auth:api']],
    )
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

http://localhost:8000/broadcasting/auth returns 200 Ok Code with an auth and channel_data property.

Steps To Reproduce

  1. Laravel new test-project
  2. php artisan install:api
  3. php artisan install:broadcasting
    adding Broadcast::routes(['middleware' => ['api', 'auth:sanctum']]); to channels.php
  4. php artisan reverb:start
  5. On Nuxt3:
import Echo from "laravel-echo"
import Pusher from "pusher-js"
import type { ChannelAuthorizationCallback } from "pusher-js"
window.Pusher = Pusher
export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig()
  console.log(config.public)
  const echo = new Echo({
    withCredentials: true,
    broadcaster: "reverb",
    key: config.public.REVERB_KEY,
    wsHost: config.public.REVERB_HOST,
    scheme: config.public.REVERB_SCHEME,
    wsPort: 8080,
    host: config.public.REVERB_HOST,

    enabledTransports: ["ws", "wss"],
    encrypted: false,
    forceTLS: false,
    authorizer: (channel: any, options: any) => {
      return {
        authorize: async (
          socketId: string,
          callback: ChannelAuthorizationCallback
        ) => {
          // request xsrf token
          await useFetch("http://localhost:8000/sanctum/csrf-cookie", {
            method: "GET",
            credentials: "include",
          })
          const token = useCookie("XSRF-TOKEN").value || ""
          console.log(token)
          await useFetch("http://localhost:8000/broadcasting/auth", {
            method: "POST",
            credentials: "include",

            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              "X-XSRF-TOKEN": token,
              Authorization: "Bearer " + token,
            },

            body: {
              socket_id: socketId,
              channel_name: channel.name,
            },
          })
            .then((data) => {
              console.log("ALERT123")
              callback(false, data)
            })
            .catch((error) => {
              console.log("ALERT123")
              callback(true, {
                auth: null,
                data: null,
              })
            })
        },
      }
    },
  })

  return {
    provide: {
      echo,
    },
  }
})

<template>
  <div></div>
</template>

<script lang="ts" setup>
  const { $echo } = useNuxtApp()

  //presence channel test
  onMounted(() => {
    $echo
      .join("test-abc")
      .here((users) => {
        console.log(users)
      })
      .joining((user) => {
        console.log(user)
      })

      .error((error) => {
        console.log(error)
      })
  })
</script>

<style></style>
@heinergiehl heinergiehl changed the title Laravel Echo return AuthError in error callback. Laravel Echo returns AuthError in error callback Feb 24, 2025
@crynobone
Copy link
Member

Hey there, thanks for reporting this issue.

We'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue as one separate commit on the main/master branch and share the repository here?

Please make sure that you have the latest version of the Laravel installer in order to run this command. Please also make sure you have both Git & the GitHub CLI tool properly set up.

laravel new bug-report --github="--public"

Do not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants