


When developing a WebSocket server using Netty4, how do you ensure that the browser correctly recognizes the 401 response?
Netty4 WebSocket Server: Correctly handle browser 401 responses
When developing WebSocket servers using Netty4, it is often necessary to verify the client token. If verification fails, the server should return the 401 status code and close the connection. However, browsers sometimes fail to receive this response correctly. This article will explain in detail how to resolve this issue.
Question: Use var socket = new WebSocket("ws://127.0.0.1:18080/ws?token=xxxx");
to connect to the server, and the server verifies the token. On failure, the server returns 401 and closes the connection, but the browser does not receive a 401 response. The server code snippet is as follows:
private void httpResponse401(ChannelHandlerContext ctx, FullHttpRequest request){ FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.UNAUTHORIZED); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(request); }
Cause: The problem lies in the WebSocket handshake stage. The handshake request is an HTTP request, but after the handshake is successful, the communication is no longer an HTTP protocol. Therefore, the 401 response must be returned in the handshake phase.
Solution: Verify the token in the code that handles the WebSocket handshake request. If the verification fails, the 401 response is directly returned, and the WebSocket connection establishment logic is not executed.
Improved code example:
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; String token = extractTokenFromRequest(request); //Extract the helper function of Token if (!validateToken(token)) { httpResponse401(ctx, request); return; } // Token verification is passed, continue WebSocket handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), null, false); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), request); } } else if (msg instanceof WebSocketFrame) { // Process WebSocket frames} } private String extractTokenFromRequest(FullHttpRequest request) { String uri = request.uri(); String[] parts = uri.split("\\?"); if (parts.length > 1) { String[] params = parts[1].split("&"); for (String param : params) { String[] keyValue = param.split("="); if (keyValue.length == 2 && keyValue[0].equals("token")) { return keyValue[1]; } } } return null; } private boolean validateToken(String token) { // Implement the token verification logic here return token != null && token.equals("validToken"); // Example, replace with the actual verification logic} private void httpResponse401(ChannelHandlerContext ctx, FullHttpRequest request) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(request); }
By performing token verification during the handshake phase and returning a 401 response, the browser can correctly identify the reason for the connection to close, thus enabling a more robust WebSocket server. extractTokenFromRequest
function enhances the robustness of Token extraction. Please replace token
verification in the example with your actual verification logic.
The above is the detailed content of When developing a WebSocket server using Netty4, how do you ensure that the browser correctly recognizes the 401 response?. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor