admin管理员组

文章数量:1279185

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.

Does anyone know what the issue is?

Steps To Reproduce:

  1. laravel new test-project
  2. php artisan install:api
  3. php artisan install:broadcasting
  4. adding Broadcast::routes(['middleware' => ['api', 'auth:sanctum']]); to channels.php
  5. php artisan reverb:start
  6. 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,
    },
  }
})

  1. on an Nuxt3 index page:
<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>

本文标签: