fix:握手认证优化

This commit is contained in:
zhongzb
2023-07-02 23:04:10 +08:00
parent f26a08b229
commit c10e03727c
3 changed files with 22 additions and 4 deletions

View File

@@ -20,6 +20,7 @@ public class HttpHeadersHandler extends ChannelInboundHandlerAdapter {
ip = address.getAddress().getHostAddress();
}
NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
ctx.pipeline().remove(this);
}
ctx.fireChannelRead(msg);
}

View File

@@ -1,5 +1,6 @@
package com.abin.mallchat.custom.user.websocket;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.abin.mallchat.custom.user.domain.enums.WSReqTypeEnum;
@@ -66,7 +67,10 @@ public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<Tex
}
} else if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
getService().connect(ctx.channel());
getService().authorize(ctx.channel(), new WSAuthorize(NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN)));
String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN);
if (StrUtil.isNotBlank(token)) {
getService().authorize(ctx.channel(), new WSAuthorize(token));
}
}
super.userEventTriggered(ctx, evt);
}

View File

@@ -1,6 +1,8 @@
package com.abin.mallchat.custom.user.websocket;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
@@ -19,9 +21,20 @@ public class WebSocketHandshakeHandler extends ChannelInboundHandlerAdapter {
WebSocketServerHandshakerFactory handshakeFactory = new WebSocketServerHandshakerFactory(
request.uri(), token, false);
WebSocketServerHandshaker handshake = handshakeFactory.newHandshaker(request);
handshake.handshake(ctx.channel(), request);
// 手动触发WebSocket握手状态事件
ctx.pipeline().fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
final ChannelFuture handshakeFuture = handshake.handshake(ctx.channel(), request);
ctx.pipeline().remove(this);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
// 手动触发WebSocket握手状态事件
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
}
}
});
} else {
super.channelRead(ctx, msg);
}