Окно 10 Как заставить Tomcat 9 работать по https - PullRequest
1 голос
/ 20 февраля 2020

Моя цель - использовать javascript webkitGetUserMedia для доступа к веб-камере и использовать java WebSocket в моей сети LAN. Я использовал apache -tomcat-9.0.20 с apache -maven-3.6.3 и eclipse ide. Я могу получить доступ к http в моей сети просто отлично. Тем не менее, с https я могу получить доступ только на самом сервере. Я попытался отключить брандмауэр, изменив имя хоста по умолчанию на имя компьютера сервера. Но ничего не вижу, чтобы работать. Пожалуйста, помните, что веб-камере нужен https для использования, и я смог использовать свой код в своей сети с услугой apache, изменив только jsp на php, поэтому я действительно сомневаюсь, что это проблема с брандмауэром.

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 --><Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    <!-- A "Connector" using the shared thread pool-->
  
    <Connector connectionTimeout="20000" executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
  
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
  
    <Connector SSLEnabled="true" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol">
    </Connector>

    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
   
    <Connector SSLEnabled="true" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol">
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol"/>
        <SSLHostConfig>
            <Certificate certificateChainFile="C:\Users\spjpi\Desktop\localhost.pkipath" certificateFile="C:\Users\spjpi\Desktop\localhost.cer" certificateKeyFile="C:\Users\spjpi\Desktop\localhost.pem" type="RSA"/>
        </SSLHostConfig>
    </Connector>
  

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine defaultHost="localhost" name="Catalina">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/>

      <Context docBase="camera" path="/camera" reloadable="true" source="org.eclipse.jst.j2ee.server:camera"/></Host>
    </Engine>
  </Service>
</Server>

1 Ответ

4 голосов
/ 27 февраля 2020

Во-первых, в вашем примере конфигурации вы регистрируете несколько раз одни и те же порты (2x8080 и 2x8443), поэтому ваш сервер будет выдавать ошибки в вашей консоли.

Убедитесь, что для каждого порта зарегистрирован только один разъем. По-другому вы получите исключение, подобное этому:

27-Feb-2020 01: 56: 22.744 INFO [main] org. apache .coyote.AbstractProtocol.init Initializing ProtocolHandler [ "http-nio-8080"]
27-Feb-2020 01: 56: 22.783 INFO [основная] организация. apache .coyote.AbstractProtocol.init Инициализация ProtocolHandler ["http-nio-8080"]
27-фев-2020 01: 56: 22.795 SEVERE [main] org. apache .catalina.util.LifecycleBase.handleSubClassException Не удалось инициализировать компонент [Connector [HTTP / 1.1-8080]]
org. apache. catalina.LifecycleException: ошибка инициализации обработчика протокола в org. apache .catalina.connector.Connector.initInternal (Connector. java: 983) в org. apache .catalina.util.LifecycleBase.init (LifecycleBase. java: 136) в орг. apache .catalina.core.StandardService.initInternal (StandardService. java: 533) в орг. apache .catalina.util.LifecycleBase.init (LifecycleBase. java: 136) в орг. apache .catalina.core.StandardServer.initInternal (StandardServer. java: 1059) в орг. apache .catalina.u til.LifecycleBase.init (LifecycleBase. java: 136) в орг. apache .catalina.startup.Catalina.load (Catalina. java: 584) в орг. apache .catalina.startup.Catalina. запуск (Каталина. java: 621) в sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl. java: 62) в sun.refmphoho java: 43) в java .lang.reflect.Metod.invoke (Метод. java: 498) в орг. apache .catalina.startup. Bootstrap .start (Bootstrap. java: 344) в орг. apache .catalina.startup. Bootstrap .main (Bootstrap. java: 475) Причина: java. net .BindException: Адрес уже используется на солнце .nio.ch. Net .bind0 (родной метод) в sun.nio.ch. Net .bind (Net. java: 433) в sun.nio.ch. Net .bind ( Net. java: 425) в sun.nio.ch.ServerSocketChannelImpl.bind (ServerSocketChannelImpl. java: 223) в sun.nio.ch.ServerSocketAdaptor.bind (ServerSocketAdaptor. java: 74) в организации . apache .tomcat.util. net .NioEndpoint.initServerS ocket (NioEndpoint. java: 248) в орг. apache .tomcat.util. net .NioEndpoint.bind (NioEndpoint. java: 222) в орг. apache .tomcat.util. net .AbstractEndpoint.bindWithCleanup (AbstractEndpoint. java: 1119) в орг. apache .tomcat.util. net .AbstractEndpoint.init (AbstractEndpoint. java: 1132) в орг. apache .coyote. AbstractProtocol.init (AbstractProtocol. java: 557) в орг. apache .coyote.http11.AbstractHttp11Protocol.init (AbstractHttp11Protocol. java: 74) в орг. apache .catalina.connector.Connector.initInternal ( Разъем. java: 980)
... 13 more

Таким образом, вы должны выбрать одну из этой конфигурации для порта 8080:

<!-- A "Connector" represents an endpoint by which requests are received
     and responses are returned. Documentation at :
     Java HTTP Connector: /docs/config/http.html
     Java AJP  Connector: /docs/config/ajp.html
     APR (HTTP/AJP) Connector: /docs/apr.html
     Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
<!-- A "Connector" using the shared thread pool-->

<!--<Connector connectionTimeout="20000" executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>-->

Или с помощью пул общих потоков:

<!-- A "Connector" represents an endpoint by which requests are received
     and responses are returned. Documentation at :
     Java HTTP Connector: /docs/config/http.html
     Java AJP  Connector: /docs/config/ajp.html
     APR (HTTP/AJP) Connector: /docs/apr.html
     Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<!--<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>-->
<!-- A "Connector" using the shared thread pool-->

<Connector connectionTimeout="20000" executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

Аналогичный случай с вашим SSL-портом 8443:

    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 This connector uses 
        the NIO implementation. The default SSLImplementation will depend on the 
        presence of the APR/native library and the useOpenSSL attribute of the AprLifecycleListener. 
        Either JSSE or OpenSSL style configuration may be used regardless of the 
        SSLImplementation selected. JSSE style configuration is used below. -->

    <Connector SSLEnabled="true" maxThreads="150" port="8443"
        protocol="org.apache.coyote.http11.Http11NioProtocol">
        <SSLHostConfig>
            <Certificate
                certificateChainFile="C:\Users\spjpi\Desktop\localhost.pkipath"
                certificateFile="C:\Users\spjpi\Desktop\localhost.cer"
                certificateKeyFile="C:\Users\spjpi\Desktop\localhost.pem"
                type="RSA" />
        </SSLHostConfig>
    </Connector>

    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2 This 
        connector uses the APR/native implementation which always uses OpenSSL for 
        TLS. Either JSSE or OpenSSL style configuration may be used. OpenSSL style 
        configuration is used below. -->

    <!--<Connector SSLEnabled="true" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol">
        <UpgradeProtocol
            className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate
                certificateChainFile="C:\Users\spjpi\Desktop\localhost.pkipath"
                certificateFile="C:\Users\spjpi\Desktop\localhost.cer"
                certificateKeyFile="C:\Users\spjpi\Desktop\localhost.pem"
                type="RSA" />
        </SSLHostConfig>
    </Connector>-->

С протоколом Http / 2:

    <!--<Connector SSLEnabled="true" maxThreads="150" port="8443"
        protocol="org.apache.coyote.http11.Http11NioProtocol">
        <SSLHostConfig>
            <Certificate
                certificateChainFile="C:\Users\spjpi\Desktop\localhost.pkipath"
                certificateFile="C:\Users\spjpi\Desktop\localhost.cer"
                certificateKeyFile="C:\Users\spjpi\Desktop\localhost.pem"
                type="RSA" />
        </SSLHostConfig>
    </Connector>-->

    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2 This 
        connector uses the APR/native implementation which always uses OpenSSL for 
        TLS. Either JSSE or OpenSSL style configuration may be used. OpenSSL style 
        configuration is used below. -->

    <Connector SSLEnabled="true" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol">
        <UpgradeProtocol
            className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate
                certificateChainFile="C:\Users\spjpi\Desktop\localhost.pkipath"
                certificateFile="C:\Users\spjpi\Desktop\localhost.cer"
                certificateKeyFile="C:\Users\spjpi\Desktop\localhost.pem"
                type="RSA" />
        </SSLHostConfig>
    </Connector>

Допустимый пример конфигурации (с моим собственным хранилищем ключей) может быть:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="/Users/myuser/dev/keystore/keystore-dev.jks"
              certificateKeyAlias="localhost" certificateKeystorePassword="localhost"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

    <Engine name="Catalina" defaultHost="localhost">

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
      </Host>
    </Engine>
  </Service>
</Server>

Если все настроено нормально, запустите ваш сервер, и вы увидите в своих журналах что-то вроде этого:

27 февраля -2020 02: 15: 14.234 ИНФОРМАЦИЯ [основная] организация. apache .coyote.AbstractProtocol.init Инициализация ProtocolHandler ["http-nio-8080"]
27-февраль-2020 02: 15: 14.268 ИНФОРМАЦИЯ [основная] org. apache .coyote.AbstractProtocol.init Инициализация ProtocolHandler ["https-jsse-nio-8443"]
27-Feb-2020 02: 15: 14.473 INFO [главная] org. apache .coyote.AbstractProtocol .init Initializing ProtocolHandler ["ajp-nio-8009"]
27-Feb-2020 02: 15: 14.475 INFO [основная] организация. apache. catalina.startup.Catalina.load Инициализация сервера за [828] миллисекунд
27-февраля-2020 02: 15: 14.500 INFO [главная] org. apache .catalina.core.StandardService.startInternal Запуск службы [Каталина]
27-Feb-2020 02: 15: 14.500 ИНФОРМАЦИЯ [основная] организация. apache .catalina.core.StandardEngine.startInternal Запуск двигателя сервлета: [Apache Tomcat / 9.0.20]

....

27-Feb-2020 02: 15: 15.144 ИНФОРМАЦИЯ [основная] организация. apache .coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080" ]
27-февраля-2020 02: 15: 15.158 ИНФОРМАЦИЯ [главная] org. apache .coyote.AbstractProtocol.start Starting ProtocolHandler ["https-jsse-nio-8443"]
27-февраль-2020 02: 15: 15.164 INFO [главная] org. apache .coyote.AbstractProtocol.start Запуск протокола ProtocolHandler ["ajp-nio-8009"]
27-Feb-2020 02: 15: 15.166 INFO [основная] орг. apache .catalina.startup.Catalina.start Запуск сервера за [690] миллисекунд

После этого протестируйте свой сервер локально из браузера или командной строки (с помощью curl, wget, et c ):

  1. https://localhost: 8443 /

  2. https://127.0.0.1: 8443 /

  3. https://YOUR_IP: 8443 / (где YOUR_IP - IP-адрес вашего сервера, например, 192.168.0.1)

Если Ваш сертификат является самозаверяющим сертификатом (для развивающего использования) или не подписан доверенным органом, в вашем браузере появится сообщение об ошибке: «Ваше соединение не является частным» (например, ERR_CERT_AUTHORITY_INVALID). Таким образом, вам нужно поместить свой сертификат в хранилище доверенных сертификатов, принять подписку с незащищенным сертификатом или использовать сертификат готовности к работе, подписанный доверенным органом (для получения дополнительной информации об этом: решить недопустимую проблему SSL / TLS ).

Имейте в виду, что по умолчанию соединитель tomcat будет прослушивать все адреса локальных серверов.

Для вашей информации, если вы хотите ограничить IP-адреса привязки, у соединителя есть атрибут 'address', который вы можете указать с помощью IP.

Из ссылки Tomcat: docs

address

Для серверов с более чем одним IP-адресом этот атрибут указывает, какой адрес будет использоваться для прослушивания на указанном порту. По умолчанию соединитель будет прослушивать все локальные адреса. Если JVM не настроена иначе с использованием системных свойств, соединители на основе Java (NIO, NIO2) будут прослушивать как адреса IPv4, так и адреса IPv6 при настройке либо 0.0.0.0, либо ::. APR / собственный соединитель будет прослушивать IPv4-адреса только в том случае, если настроено 0.0.0.0, и будет прослушивать IPv6-адреса (и необязательно IPv4-адреса в зависимости от настройки ipv6onlyv6), если настроено с помощью ::.

Если вы не можете получить доступ к вашему серверу локально с указанными URL-адресами, укажите свои журналы и сообщение об ошибке.

В противном случае, если вам удастся получить доступ ко всем этим URL-адресам локально, попробуйте с удаленного хоста:

  1. Убедитесь, что IP-адрес сервера доступен с удаленного терминала (например, ping)
  2. Попробуйте получить доступ к https://YOUR_IP: 8443 / http://YOUR_IP: 8080 / ) в браузере
  3. Если вы получили сообщение об ошибке «Ваше соединение не является частным», нажмите, чтобы увидеть более подробную информацию, и подтвердите небезопасным . В этом случае, как уже отмечалось ранее, проверьте, что ваш сертификат действителен / не истек, а полномочия находятся в ваших доверенных сертификатах.
  4. Если вы получаете ошибку другого типа, проверьте, что ваш сервер и ваш удаленный клиент / p c отключил правила брандмауэра (обе стороны) и проверьте доступ к удаленному порту с помощью te lnet.
  5. Проверьте конфигурацию / etc / hosts и iptables.
  6. Если проблема не устранена, укажите больше информации, пожалуйста.

Надеюсь, это поможет,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...