尝试通过Pusher和Laravel Echo在API中进行身份验证时遇到错误401

时间:2019-04-21 16:12:36

标签: laravel sockets authentication websocket

我试图在laravel中建立一个聊天窗口以学习网络套接字。但是,当我尝试使用“私人频道”或“在线状态”频道时,出现错误401“未经身份验证”,因此,如果我无法进行身份验证,则用户将无法进入该频道。

我的config / app.php没有注释行

我正在使用vuejs和laravel构建SPA,因此有必要使用中间件api:auth

进行身份验证

BroadcastServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //Broadcast::routes(['middleware' => 'auth:api']);
       Broadcast::routes(['middleware' => 'auth:api']);

        require base_path('routes/channels.php');
    }
}

channels.php

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

Broadcast::channel('salachat.{chatid}', function ($user, $chatid) {
    return $user;
});

MessageChat.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\mensajes;

class MessageChat implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct(mensajes $message){
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('salachat.'. $this->message->Chat_id);
    }
}

bootstrap.js

 import Echo from 'laravel-echo'
 window.Pusher = require('pusher-js');

 window.Echo = new Echo({
    //authEndpoint: '/broadcasting/auth',
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    //cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    //encrypted: true,
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    auth: {
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('PinguToken'),
            'X-CSRF-TOKEN': token.content,
        },
    }
 });

呼叫频道

Echo.join('salachat.'+self.idchat)
                        .listen('MessageChat', (event)=>{
                            console.log(event);
                            self.messagechat.push(event.message);
                        });

0 个答案:

没有答案