如何使用广播身份验证修复419错误

时间:2019-04-24 07:10:05

标签: laravel-5 broadcast pusher

在我的Laravel Framework 5.7 / Vuejs 2.6中,我使用jwt.auth并安装推送器

我检查了页面https://imgur.com/a/CveJ6jh的xsfr令牌,但在http://local/broadcasting/auth请求中出现419错误,并打开了该URL的响应,我看到页面已过期消息。
在app / Events / NewMessage.php中:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Message;

class NewMessage
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message= $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('messages.'.$this->message->to);
    }
    public function broadcastWith()
    {
        return ['messages' => $this->message];
    }

}

在routes / channels.php中:

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

但是我没有从上面看到任何调试信息。

我使用了先前应用程序中的pusher参数。我认为他们一定没事。否则我会有其他错误?

和in vue组件:

mounted() {
    Echo.private(`messages.${this.customerRow.id}`)
        .listen('NewMessage', (e) => {
            this.hanleIncoming(e.message);
        });

我想念什么?

谢谢!

2 个答案:

答案 0 :(得分:3)

要解决此问题,您需要像这样在广播路由上添加中间件。

Broadcast::routes(['middleware' => 'auth:api']);

在app / Providers / BroadcastServiceProvider.php上

答案 1 :(得分:1)

此错误的原因是Laravel期望a CSRF token

您有两个选择:

  1. Include the CSRF token(为安全起见更好)
  2. Disable CSRF for this URL