From 0cc840cadfb50e143ddf942b1d953f9330485974 Mon Sep 17 00:00:00 2001 From: zbzbzzz Date: Sat, 1 Jul 2023 16:58:32 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat:ws=E6=8F=A1=E6=89=8B=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/common/utils/JwtUtils.java | 2 +- .../common/algorithm/ac/CreateTokenTest.java | 44 +++++++++++++++++++ .../user/websocket/HttpHeadersHandler.java | 3 +- .../custom/user/websocket/NettyUtil.java | 1 + .../NettyWebSocketServerHandler.java | 6 +-- 5 files changed, 50 insertions(+), 6 deletions(-) create mode 100644 mallchat-common/src/test/java/com/abin/mallchat/common/common/algorithm/ac/CreateTokenTest.java diff --git a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JwtUtils.java b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JwtUtils.java index af02421..fe2a97e 100644 --- a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JwtUtils.java +++ b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JwtUtils.java @@ -26,7 +26,7 @@ public class JwtUtils { /** * token秘钥,请勿泄露,请勿随便修改 */ - @Value("jwt.secret") + @Value("${mallchat.jwt.secret}") private String secret; private static final String UID_CLAIM = "uid"; diff --git a/mallchat-common/src/test/java/com/abin/mallchat/common/common/algorithm/ac/CreateTokenTest.java b/mallchat-common/src/test/java/com/abin/mallchat/common/common/algorithm/ac/CreateTokenTest.java new file mode 100644 index 0000000..50908e4 --- /dev/null +++ b/mallchat-common/src/test/java/com/abin/mallchat/common/common/algorithm/ac/CreateTokenTest.java @@ -0,0 +1,44 @@ +package com.abin.mallchat.common.common.algorithm.ac; + + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.auth0.jwt.interfaces.JWTVerifier; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import java.util.Date; + + +@Slf4j +public class CreateTokenTest { + + @Test + public void create(){ + String token = JWT.create() + .withClaim("uid", 123L) // 只存一个uid信息,其他的自己去redis查 + .withClaim("createTime", new Date()) + .sign(Algorithm.HMAC256("dsfsdfsdfsdfsd")); // signature + log.info("生成的token为 {}",token); + + + try { + JWTVerifier verifier = JWT.require(Algorithm.HMAC256("dsfsdfsdfsdfsd")).build(); + DecodedJWT jwt = verifier.verify(token); + log.info(jwt.getClaims().toString()); + } catch (Exception e) { + log.info("decode error,token:{}", token, e); + } + } + + @Test + public void verifyToken(){ + String token = JWT.create() + .withClaim("uid", 1) // 只存一个uid信息,其他的自己去redis查 + .withClaim("createTime", new Date()) + .sign(Algorithm.HMAC256("dsfsdfsdfsdfsd")); // signature + log.info("生成的token为{}",token); + } +} diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java index 72f4b3c..df64b64 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java @@ -10,7 +10,6 @@ import org.apache.commons.lang3.StringUtils; import java.net.InetSocketAddress; public class HttpHeadersHandler extends ChannelInboundHandlerAdapter { - private AttributeKey key = AttributeKey.valueOf("Id"); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { @@ -22,6 +21,8 @@ public class HttpHeadersHandler extends ChannelInboundHandlerAdapter { ip = address.getAddress().getHostAddress(); } NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip); + String token = headers.get("token"); + NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token); } ctx.fireChannelRead(msg); } diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyUtil.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyUtil.java index d2bacef..79daafa 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyUtil.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyUtil.java @@ -12,6 +12,7 @@ import io.netty.util.AttributeKey; public class NettyUtil { + public static AttributeKey TOKEN = AttributeKey.valueOf("token"); public static AttributeKey IP = AttributeKey.valueOf("ip"); public static AttributeKey UID = AttributeKey.valueOf("uid"); diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java index 7f1c981..b4b5734 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java @@ -66,6 +66,7 @@ public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler Date: Sat, 1 Jul 2023 20:37:43 +0800 Subject: [PATCH 2/3] =?UTF-8?q?feat:ws=E6=8F=A1=E6=89=8B=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/websocket/HttpHeadersHandler.java | 22 +++++++++++++++---- .../NettyWebSocketServerHandler.java | 5 ++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java index df64b64..b5112e4 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java @@ -1,7 +1,10 @@ package com.abin.mallchat.custom.user.websocket; +import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.URLUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.util.AttributeKey; @@ -14,16 +17,27 @@ public class HttpHeadersHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { - HttpHeaders headers = ((FullHttpRequest) msg).headers(); + FullHttpRequest request = (FullHttpRequest) msg; + HttpHeaders headers = request.headers(); String ip = headers.get("X-Real-IP"); if (StringUtils.isEmpty(ip)) {//如果没经过nginx,就直接获取远端地址 InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); ip = address.getAddress().getHostAddress(); } + + String[] uriSplit = request.uri().split("[?]"); + FullHttpRequest modifiedRequest = new DefaultFullHttpRequest(request.protocolVersion(), request.method(), uriSplit[0]); + modifiedRequest.headers().add(headers); + modifiedRequest.content().writeBytes(request.content()); + + NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip); - String token = headers.get("token"); - NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token); + if (uriSplit.length>=2) { + NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, uriSplit[1]); + } + ctx.fireChannelRead(modifiedRequest); + }else { + super.channelRead(ctx, msg); } - ctx.fireChannelRead(msg); } } \ No newline at end of file diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java index b4b5734..e89030e 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServerHandler.java @@ -93,7 +93,10 @@ public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler Date: Sun, 2 Jul 2023 15:26:00 +0800 Subject: [PATCH 3/3] =?UTF-8?q?feat:ws=E6=8F=A1=E6=89=8B=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E8=AE=A4=E8=AF=81=20=E4=BB=A5Sec-Websocket-Protocol=E7=9A=84?= =?UTF-8?q?=E5=BD=A2=E5=BC=8F=E4=BC=A0=E9=80=92token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/websocket/HttpHeadersHandler.java | 21 ++------------ .../user/websocket/NettyWebSocketServer.java | 3 +- .../websocket/WebSocketHandshakeHandler.java | 29 +++++++++++++++++++ 3 files changed, 32 insertions(+), 21 deletions(-) create mode 100644 mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/WebSocketHandshakeHandler.java diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java index b5112e4..6b55b91 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/HttpHeadersHandler.java @@ -1,13 +1,9 @@ package com.abin.mallchat.custom.user.websocket; -import cn.hutool.core.util.StrUtil; -import cn.hutool.core.util.URLUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; -import io.netty.util.AttributeKey; import org.apache.commons.lang3.StringUtils; import java.net.InetSocketAddress; @@ -17,27 +13,14 @@ public class HttpHeadersHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { - FullHttpRequest request = (FullHttpRequest) msg; - HttpHeaders headers = request.headers(); + HttpHeaders headers = ((FullHttpRequest) msg).headers(); String ip = headers.get("X-Real-IP"); if (StringUtils.isEmpty(ip)) {//如果没经过nginx,就直接获取远端地址 InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); ip = address.getAddress().getHostAddress(); } - - String[] uriSplit = request.uri().split("[?]"); - FullHttpRequest modifiedRequest = new DefaultFullHttpRequest(request.protocolVersion(), request.method(), uriSplit[0]); - modifiedRequest.headers().add(headers); - modifiedRequest.content().writeBytes(request.content()); - - NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip); - if (uriSplit.length>=2) { - NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, uriSplit[1]); - } - ctx.fireChannelRead(modifiedRequest); - }else { - super.channelRead(ctx, msg); } + ctx.fireChannelRead(msg); } } \ No newline at end of file diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServer.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServer.java index 4ebf470..b70b867 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServer.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/NettyWebSocketServer.java @@ -10,7 +10,6 @@ import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; -import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.stream.ChunkedWriteHandler; @@ -89,7 +88,7 @@ public class NettyWebSocketServer { * 4. WebSocketServerProtocolHandler 核心功能是把 http协议升级为 ws 协议,保持长连接; * 是通过一个状态码 101 来切换的 */ - pipeline.addLast(new WebSocketServerProtocolHandler("/")); + pipeline.addLast(new WebSocketHandshakeHandler()); // 自定义handler ,处理业务逻辑 pipeline.addLast(new NettyWebSocketServerHandler()); } diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/WebSocketHandshakeHandler.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/WebSocketHandshakeHandler.java new file mode 100644 index 0000000..bc1119f --- /dev/null +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/websocket/WebSocketHandshakeHandler.java @@ -0,0 +1,29 @@ +package com.abin.mallchat.custom.user.websocket; + + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; +import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; +import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; + +public class WebSocketHandshakeHandler extends ChannelInboundHandlerAdapter { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof FullHttpRequest) { + FullHttpRequest request = (FullHttpRequest) msg; + String token = request.headers().get("Sec-Websocket-Protocol"); + NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token); + // 构建WebSocket握手处理器 + 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); + } else { + super.channelRead(ctx, msg); + } + } +}