Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P17-Final): Websocket Communication User Authentication Logic Optimization
Previously, in Websocket communication, user authentication was very rude, that is, each time it obtained from the request field api_token
, and then determined whether the corresponding user record exists on the server:
if (!empty($data['api_token']) && ($user = User::where('api_token', $data['api_token'])->first())) {
...
}
We can optimize this certification process like this:
$websocket->loginUsing()
the method provided in this connection on a user ID, a user authentication bound state;$websocket->getUserId()
obtaining the user ID authentication on the connection method;$websocket->logout()
the method binding canceled user authentication status.Let’s take a look at how to do it.
Let socket.io
relevant routes through Laravel certified middleware auth:api
filtration, unauthenticated users can not access, which can be SocketIOController
achieved constructor controller:
public function __construct()
{
$this->middleware('auth:api');
}
Then adjust the code corresponding to the middleware (in app/Http/Middleware/Authenticate.php
), to throw unauthenticated user authentication error alarm, not a jump to login
route:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
throw new AuthorizationException("Websocket connection can only be established after login");
}
}
Next, we went to the front, Socket.io need to specify the client establishes a connection api_token
request field, so that the server can read and authenticate automatically, modify the socket.js
code as follows:
...
import store from "./store";
let api_token = store.state.userInfo.token;
const socket = io('http://webchats.test?api_token=' + api_token);
...
Finally, open routes/websocket.php
and adjust the user authentication related code as follows:
WebsocketProxy::on('connect', function (WebSocket $websocket, Request $request) {
// Send welcome message
$websocket->setSender($request->fd);
// Binding authentication user information when establishing a connection
$websocket->loginUsing(auth('api')->user());
});
WebsocketProxy::on('room', function (WebSocket $websocket, $data) {
if ($userId = $websocket->getUserId()) {
$user = User::find($userId);
...
} else {
$websocket->emit('login', 'Login to enter chat room');
}
});
WebsocketProxy::on('message', function (WebSocket $websocket, $data) {
if ($userId = $websocket->getUserId()) {
$user = User::find($userId);
...
} else {
$websocket->emit('login', 'Login to enter chat room');
}
});
...
WebsocketProxy::on('disconnect', function (WebSocket $websocket, $data) {
roomout($websocket, $data);
$websocket->logout();
});
...
Because here Websocket
by default only provides a getUserId
method does not provide getUser
a method, so even after the query again to authenticate the user to obtain more information, you may also be based on the underlying loginUsingUserId
and getUserId
write their own implementation loginUsingUser
and getUser
the realization of logic, there is no longer expand in detail. In addition, since the user Websocket connection can be established, so after the certification websocket.php
of the login
realization seems to be the need for reconstruction, interested students can themselves to think and realize, college is king here when the initiate, provide some general ideas and programs, more details left to your own Go explore.
The introduction to Swoole from the beginning to the actual combat is briefly introduced here. Next, the academy will continue to Laravel from the entry to the mastery of the writing of the tutorial, and to focus more on the use and promotion of Golang. Of course, the PHP fpm framework will first promote Laravel. As for the subsequent scale of microservice refactoring, Golang is recommended (the Java party can bypass it).
#laravel #swoole #vue