Websocket实现token认证方式
1.将token放到header中
java客户端代码展示
@Slf4j
public class Demo {
public static void main(String[] args) {
String currentPersonId = "wangwu";
WebSocketClient webSocketClient = null;
try {
webSocketClient = new MyWebSocketClient(new URI("ws://127.0.0.1:8080/websocket/" + currentPersonId));
} catch (URISyntaxException e) {
e.printStackTrace();
}
webSocketClient.addHeader("token", "sadfasdfasdfsdf");
webSocketClient.connectBlocking();
log.info("连接成功!");
Scanner scanner = new Scanner(System.in);
while (true) {
System.err.println(currentPersonId + " -> ");
String message = scanner.nextLine();
webSocketClient.send(message);
}
}
}
2.将token放在url上
ws://xxx.com?token=asdfjhsakjdfhskdjhfa
java客户端代码展示
@Slf4j
public class Demo {
public static void main(String[] args) {
String currentPersonId = "wangwu";
WebSocketClient webSocketClient = null;
try {
webSocketClient = new MyWebSocketClient(new URI("ws://127.0.0.1:8080/websocket/" + currentPersonId
+ "?token=asdfjhsakjdfhskdjhfa"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
webSocketClient.connectBlocking();
log.info("连接成功!");
Scanner scanner = new Scanner(System.in);
while (true) {
System.err.println(currentPersonId + " -> ");
String message = scanner.nextLine();
webSocketClient.send(message);
}
}
}
3.将token放到 WebSockets的Sec-WebSocket-Protocol中
java客户端代码展示
@Slf4j
public class Demo {
public static void main(String[] args) {
String currentPersonId = "wangwu";
WebSocketClient webSocketClient = null;
try {
webSocketClient = new MyWebSocketClient(new URI("ws://127.0.0.1:8080/websocket/" + currentPersonId));
} catch (URISyntaxException e) {
e.printStackTrace();
}
webSocketClient.addHeader("Sec-WebSocket-Protocol", "sadfasdfasdfsdf");
webSocketClient.connect();
webSocketClient.connectBlocking();
log.info("连接成功!");
Scanner scanner = new Scanner(System.in);
while (true) {
System.err.println(currentPersonId + " -> ");
String message = scanner.nextLine();
webSocketClient.send(message);
}
}
}
第一种方式很好理解,正常http协议也是这么做的;但是前端的websocket client js 不支持传递header,所以就出现了第二种和第三种写法。其中尤其要注意第三种写法,使用第三种写法其实是使用websocket子协议这个请求头的key,所以你的服务端需要在response中返回同样的headr的key和value,否则客户端会直接断开连接。文章来源:https://www.toymoban.com/news/detail-527680.html
java服务端代码展示
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import java.util.Map;
public class MyWebSocketInterceptor extends HttpSessionHandshakeInterceptor {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
logger.info("[MyWebSocketInterceptor#BeforeHandshake] Request from " + request.getRemoteAddress().getHostString());
if (request instanceof ServletServerHttpRequest){
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
// 第一种取header中的值
// String token = serverHttpRequest.getServletRequest().getHeader("token");
// 第二种取url中的值
// String token = ((ServletServerHttpRequest) request).getServletRequest().getParameter("token");
// 第三种 需要返回相同的header
String token = serverHttpRequest.getServletRequest().getHeader("Sec-WebSocket-Protocol");
response.getHeaders().set("Sec-WebSocket-Protocol", token);
//这里做一个简单的鉴权,只有符合条件的鉴权才能握手成功
if ("token-123456".equals(token)){
return super.beforeHandshake(request, response, wsHandler, attributes);
}else {
return false;
}
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
logger.info("[MyWebSocketInterceptor#afterHandshake] Request from " + request.getRemoteAddress().getHostString());
}
}
前端代码演示
// 第二种方式 中括号内的就是子协议
const socket = new WebSocket('ws://xxx.com/ws?toekn=asdkjfhask');
// 第三种方式 中括号内的就是子协议
const socket = new WebSocket('ws://xxx.com/ws', ['my-token']);
socket.send('msg');
websocket使用springboot如何实现可以看看http://events.jianshu.io/p/1174b92e44d7文章来源地址https://www.toymoban.com/news/detail-527680.html
到了这里,关于Websocket实现token认证方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!