preface
A recent project in my company requires user authentication when creating a webSocket connection, and then, when creating a webSocket connection, carries a user authenticated cookie. All baidu, Google did not find the right way. I finally found a demo on Github, which I’ll note here.
To the chase
Since Springboot 2.0, we have integrated websocket, which can be imported directly:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Copy the code
- The service side
@ServerEndpoint(value = "/websocket")
@Component
public class CSocket {
/** * socket start */
@OnOpen
public void onOpen(Session session) {
System.out.println("connection")}/** * socket stop */
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info("session = [" + session + "], closeReason = [" + closeReason + "]");
}
/** * socket message */
@OnMessage
public void onMessage(String message) {
System.out.println("receive message is "+message);
}
@OnMessage
public void onBinaryMessage(ByteBuffer message) {
System.out.println("receive byte data");
}
@OnError
public void onError(Session session, Throwable error) { error.printStackTrace(); }}Copy the code
- The client
// Connect to the server
String uri = "ws://localhost:8080/websocket";
System.out.println("Connecting to " + uri);
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(ClientSocket.class, URI.create(uri));
} catch (Exception e) {
e.printStackTrace();
}
// The client receives the class
@ClientEndpoint
public class ClientSocket {
@OnOpen
public void onOpen(Session session) {}@OnMessage
public void onMessage(String message) {}@OnError
public void onError(Throwable t) {}}Copy the code
- WebSocket sends messages
session.getBasicRemote().sendText(message);
Copy the code
- A webSocket connection passes cookies and headers
public static Session connection(String uri, String cookieValue){
Session session = null;
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
ClientEndpointConfig cec = ClientEndpointConfig.Builder
.create().configurator(new ClientEndpointConfig.Configurator() {
public void beforeRequest(Map<String, List<String>> headers) {
System.out.println("Setting user cookie in beforeRequest ...");
if(null! = cookieValue && ! cookieValue.isEmpty()){ ArrayList<String> value =new ArrayList<>();
value.add(cookieValue);
// Set the header,
headers.put("cookie", value);
}
}
}).build();
session = container.connectToServer(ClientSocket.class, cec, URI.create(uri));
} catch (Exception e) {
e.printStackTrace();
}
return session;
}
Copy the code
conclusion
In this investigation, I searched a lot of information, most of which were to use Java-WebSocket package to connect and add header information in WebSocketClient, but I tried it but it didn’t work, maybe I tried it in the wrong way. Finally, I found an example on Github, tested it, and it worked, and everything was fine.
Reference address github.com/sivayapps/W…