Как выставить WSS «безопасный веб-сокет» с Java - PullRequest
2 голосов
/ 26 марта 2019

Я настраиваю новый сервер webSocket с использованием Java и хочу показать его в WSS, потому что мое клиентское приложение находится в HTTPS.Не могли бы вы помочь мне, пожалуйста

Я пытался изменить свой web.xml, но он не работает

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Protected resource</web-resource-name>
      <url-pattern>/*</url-pattern>
      <http-method>GET</http-method>
    </web-resource-collection>
    <!-- https -->
    <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
</web-app>

Это мой класс EndPoint

@ServerEndpoint(value = "/signalisation/{username}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
public class ChatEndpoint {
    private Session session;
    private static final Set<ChatEndpoint> chatEndpoints = new CopyOnWriteArraySet<>();
    private static HashMap<String, String> users = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) throws IOException, EncodeException {
        System.out.println("connected");
        this.session = session;
        chatEndpoints.add(this);
        users.put(session.getId(), username);

        Message message = new Message();
        message.setFrom(username);
        message.setContent("Connected!");
        broadcast(message, message.getTo());
    }

    @OnMessage
    public void onMessage(Session session, Message message) throws IOException, EncodeException {
        message.setFrom(users.get(session.getId()));
        System.out.println("messaged");

    }

    @OnClose
    public void onClose(Session session) throws IOException, EncodeException {
        System.out.println("out");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        // Do error handling here
    }

    private static void broadcast(Message message, String id) throws IOException, EncodeException {
        chatEndpoints.forEach(endpoint -> {
            if (endpoint.session.getId().equals(id)){
                synchronized (endpoint) {
                    try {
                        endpoint.session.getBasicRemote()
                                .sendObject(message);
                    } catch (IOException | EncodeException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public String getKeyFromMap(HashMap map, String value){

        for (Object o : map.keySet()) {
            if (map.get(o).equals(value))
                return o.toString();
        }
        return null;
    }

}

МойПриложение на стороне клиента

var conn = new WebSocket('ws://<IP_ADRESSE>:8080/<PATH>/signalisation/'+c);
conn.onopen = function () {
      console.log("Connected to the server");
};

Мой фактический результат:

client.js: 11 Смешанное содержимое: страница в https://IP_ADRESSE:PORT/?user=blabla' была загружена через HTTPS, но попытка подключенияк небезопасной конечной точке WebSocket 'ws: // IP_ADRESSE: 8080 / PATH / signalisation / blabla'.Этот запрос был заблокирован;эта конечная точка должна быть доступна через WSS.

...