


When developing a WebSocket server using Netty4, how do you ensure that the browser correctly recognizes the 401 response?
Apr 19, 2025 pm 03:18 PMNetty4 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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Ethereum is a decentralized application platform based on smart contracts, and its native token ETH can be obtained in a variety of ways. 1. Register an account through centralized platforms such as Binance and Ouyiok, complete KYC certification and purchase ETH with stablecoins; 2. Connect to digital storage through decentralized platforms, and directly exchange ETH with stablecoins or other tokens; 3. Participate in network pledge, and you can choose independent pledge (requires 32 ETH), liquid pledge services or one-click pledge on the centralized platform to obtain rewards; 4. Earn ETH by providing services to Web3 projects, completing tasks or obtaining airdrops. It is recommended that beginners start from mainstream centralized platforms, gradually transition to decentralized methods, and always attach importance to asset security and independent research, to

First, download the Binance App through the official channel to ensure security. 1. Android users should visit the official website, confirm that the URL is correct, download the Android installation package, and enable the "Allow to install applications from unknown sources" permission in the browser. It is recommended to close the permission after completing the installation. 2. Apple users need to use a non-mainland Apple ID (such as the United States or Hong Kong), log in to the ID in the App Store and search and download the official "Binance" application. After installation, you can switch back to the original Apple ID. 3. Be sure to enable two-factor verification (2FA) after downloading and keep the application updated to ensure account security. The entire process must be operated through official channels to avoid clicking unknown links.

Bitcoin (BTC) is the world's first decentralized digital currency. Since its debut in 2009, it has become the leader in the digital asset market with its unique encryption technology and limited supply. For users who are following the cryptocurrency space, it is crucial to keep track of their price dynamics in real time.

Ouyi is a world-leading digital asset trading platform, providing users with safe, stable and reliable digital asset trading services, and supports spot and derivative transactions of various mainstream digital assets such as Bitcoin (BTC), Ethereum (ETH). Its strong technical team and risk control system are committed to protecting every transaction of users.

When using Yandex to find the official Binance channel, you must accurately locate the official website by searching for "Binance Official Website" or "Binance Official Website"; 2. After entering the official website, find the "Download" or "App" entrance in the header or footer, and follow the official guidelines to download or obtain the officially verified installation files through the app store; 3. Avoid clicking on advertisements or third-party links throughout the process, ensure that the domain name is correct and the link is trustworthy, so as to ensure the download security.

Ethereum is a decentralized open source platform based on blockchain technology, which allows developers to build and deploy smart contracts and decentralized applications. Its native cryptocurrency is Ethereum (ETH), which is one of the leading digital currencies with market value in the world.

Open Yandex browser; 2. Search for "Binance Official Website" and enter the official website link with "binance"; 3. Click the "Download" or mobile phone icon on the page to enter the download page; 4. Select the Android version; 5. Confirm the download and obtain the installation file package; 6. After the download is completed, click on the file and follow the prompts to complete the installation; you must always download through the official channel to avoid malware, pay attention to application permission requests, and regularly update the application to ensure security. The entire process requires careful identification of the official website and reject suspicious links, and finally successfully install the Binance app.

Bitcoin (BTC) is the world's first decentralized digital currency, and it is also the pioneer and weather vane of the cryptocurrency market. Since its birth in 2009, its price volatility and technological innovation have attracted much attention from investors and technology enthusiasts around the world. Real-time grasp of its price trends is crucial for market participants.
