Reputation: 35
I need to authorize broadcasting routes through web middleware OR auth:api middleware. The code below authorizes the routes from api calls with Authorization: Bearer 'token'
as request header with socket.io-client
but it doesn't work with csrfToken
, if i use just Broadcast::routes()
it authorizes only the web subscribers
class BroadcastServiceProvider extends ServiceProvider
{
public function boot()
{
Broadcast::routes(["middleware" => ["auth:api", "web"] ]);
require base_path('routes/channels.php');
}
}
Is there any way to go through this, or maybe create two different groups of private channels and authorize them differently? I would appreciate your help with this!
Upvotes: 2
Views: 1825
Reputation: 357
The Best solution I have figured out. In your LoginController.php add authenticated function.
protected function authenticated(Request $request, $user){
$bearer_token = $user->createToken('Web'); //This will create the bearer token when user successfully login
Session::put('user_chat_token', $bearer_token->accessToken); //Store token in the session.
}
In your master.blade.php layout
<script>
var access_token = '{{ (isset($access_token)) ? $access_token : "" }}';
</script>
Now get your access_token in the bootstrap.js
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname,
auth: {
headers: {
Authorization: 'Bearer ' + access_token
}
}
});
Upvotes: 1