Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > Создание Realm в Jboss 4.2


Автор: Maverick 20.8.2007, 13:32
Уважаемые, нужен совет... переношу проект с Sun App под JBoss... возникла проблема с переносом Realm... Делаю так.... в файле ....\server\default\conf\login-config.xml прописал по пути 
Код

    <application-policy name="maverick">
       <authentication>
          <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule" flag = "required">
             <module-option name = "unauthenticatedIdentity">guest</module-option>
             <module-option name = "dsJndiName">java:/BnkDS</module-option>
             <module-option name = "principalsQuery">SELECT user_pass FROM Users WHERE user_name=?</module-option>
             <module-option name = "rolesQuery">SELECT group_name, 'Roles' FROM User_groups WHERE user_name=?</module-option>
          </login-module>
       </authentication>
    </application-policy> 


в этой базе есть указанные таблицы, старый сервер их чувствовал... 

Вот так развернут серлет в web.xml
Код

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>statist</servlet-name>
        <servlet-class>testpack.statist</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>statist</servlet-name>
        <url-pattern>/servlet/statist</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>
            index.jsp
        </welcome-file>
    </welcome-file-list>
    <security-constraint>
        <display-name>Statist</display-name>
        <web-resource-collection>
            <web-resource-name>ServletStatist</web-resource-name>
            <description/>
            <url-pattern>/servlet/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>Users</role-name>
            <role-name>Admins</role-name>
            </auth-constraint>
        <user-data-constraint>
            <description/>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
        </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>maverick</realm-name>
        </login-config>
    <security-role>
        <description/>
        <role-name>Users</role-name>
    </security-role>
    <security-role>
        <description/>
        <role-name>Admins</role-name>
    </security-role>
    </web-app>


вот так выглядит jboss-web.xml
Код

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <security-domain flushOnSessionInvalidation="false"/>
  <context-root>/TestJDBC</context-root>
  <security-role-mapping>
    <role-name>Admins</role-name>
    <group-name>MainGroup</group-name>
  </security-role-mapping>
  <security-role-mapping>
    <role-name>Users</role-name>
    <group-name>SimpleGroup</group-name>
  </security-role-mapping>  
</jboss-web>


однако до сервлета не достучаться.. просто не отзывается... 

помогите советом, плиз... 


Автор: Maverick 22.8.2007, 11:57
Видимо, так никто этого не делает в JBoss... 

Как сделать авторизацию тогда? Предложите что-нибудь...   smile 

Автор: hamsterKSU 22.8.2007, 17:30
если терпит - то завтра отвечу сутра.

Автор: hamsterKSU 22.8.2007, 18:10
http://www.hp-interex.com/UserFiles/File/white%20papers/Implementing%20J2EE%20security%20using%20JAAS%20on%20JBOSS.pdf пишут что в jboss-web.xml надо указать 
Код

<security-domain>java:/jaas/maverick</security-domain>

да точно ты не указал какой security домен юзать.
помоему jboss-web.xml достаточно только строки <security-domain>java:/jaas/maverick</security-domain>

Добавлено @ 18:12
и еше он БД по jndi имени находит?

Автор: hamsterKSU 22.8.2007, 18:27
и выложи структуру таблиц для авторизации

Автор: Maverick 23.8.2007, 10:47
таблицы вот такие
Код

CREATE TABLE [EjbEmu].[User_groups] (
    [group_name] [varchar] (255) COLLATE Cyrillic_General_CI_AS NOT NULL ,
    [user_name] [varchar] (255) COLLATE Cyrillic_General_CI_AS NOT NULL 
) ON [PRIMARY]
GO

CREATE TABLE [EjbEmu].[Users] (
    [user_name] [varchar] (255) COLLATE Cyrillic_General_CI_AS NOT NULL ,
    [user_pass] [varchar] (255) COLLATE Cyrillic_General_CI_AS NOT NULL 
) ON [PRIMARY]
GO



БД используется в других частях проекта... находит там без проблем, JNDI базы в порядке..

счас спробую jboss-web поменять...

Добавлено через 10 минут и 22 секунды
так теперь выглядит jboss-web.xml
Код

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <!-- <security-domain flushOnSessionInvalidation="false"/> -->
  <context-root>/StatistWEB</context-root>
  <security-domain>java:/jaas/maverick</security-domain>
</jboss-web>


не помогло все равно... все тоже самое... чувствуется, что защита работает... при наборе пути в браузере http://localhost:8080/StatistWEB/servlet/statist он тут же меняется на https://localhost:8443/StatistWEB/servlet/statist... то есть протокол врубается и все такое... но потом сразу  "Попытка соединения не удалась"...  

Автор: Maverick 23.8.2007, 11:11
вот это из консоли JBoss... может поможет...
Код

java:comp namespace of the StatistEAR.ear/StatistWEB.war application:

  +- UserTransaction[link -> UserTransaction] (class: javax.naming.LinkRef)
  +- env (class: org.jnp.interfaces.NamingContext)
  |   +- security (class: org.jnp.interfaces.NamingContext)
  |   |   +- realmMapping[link -> java:/jaas/maverick] (class: javax.naming.LinkRef)
  |   |   +- subject[link -> java:/jaas/maverick/subject] (class: javax.naming.LinkRef)
  |   |   +- securityMgr[link -> java:/jaas/maverick] (class: javax.naming.LinkRef)
  |   |   +- security-domain[link -> java:/jaas/maverick] (class: javax.naming.LinkRef)



вот там эти realm светятся...

Добавлено через 2 минуты и 18 секунд
хотя вот тут его нет... 
Код

java: Namespace

  +- jaas (class: javax.naming.Context)
  |   +- HsqlDbRealm (class: org.jboss.security.plugins.SecurityDomainContext)
  |   +- jbossmq (class: org.jboss.security.plugins.SecurityDomainContext)
  |   +- JmsXARealm (class: org.jboss.security.plugins.SecurityDomainContext)


Добавлено через 2 минуты и 50 секунд
я плаваю в JBoss пока... так что может - это бесполезная инфа, сорри.. 

Автор: hamsterKSU 23.8.2007, 14:15
а тебе надо именно https ?

Автор: Maverick 23.8.2007, 14:36
ага... инфа чисто конфиденциальная... 

Автор: hamsterKSU 23.8.2007, 15:05
настройки все верны!!!

трабл в следующем на JВoss не разрешено https

читаем статью http://www.i-proving.ca/space/Technologies/JBoss/Configuring+JBoss+SSL - настраиваем и все работает просто замечательно 

фаил server.xml лежит в папке сервера deploy/jboss-web.deployer/server.xml

Автор: Maverick 23.8.2007, 15:42
Создатели JBoss - странные люди, если не сказать больше...  какие нужно мозги иметь ,чтоб закрыть SSL... 

сделал все как описано - теперь браузер просто виснет на URL и все... висит и грузит... потом говорит - подключение установить не удалось.. 


Статья относиться к JBoss 4.0.2... а у меня 4.2... 

Автор: hamsterKSU 23.8.2007, 15:52
у меня 4.2 и все отлично работает

Автор: Maverick 23.8.2007, 16:33
вот мой servlet.xml 
Код

<Server>

  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />

   <!-- Use a custom version of StandardService that allows the
   connectors to be started independent of the normal lifecycle
   start to allow web apps to be deployed before starting the
   connectors.
   -->
   <Service name="jboss.web">

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" address="${jboss.bind.address}"    
         maxThreads="250" maxHttpHeaderSize="8192"
         emptySessionPath="true" protocol="HTTP/1.1"
         enableLookups="false" redirectPort="8443" acceptCount="100"
         connectionTimeout="20000" disableUploadTimeout="true" />

    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->

<!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
-->

  <!--   SSL/TLS Connector configuration using the admin devl guide keystore-->
     <Connector port="443" address="${jboss.bind.address}"
        maxThreads="100" strategy="ms" maxHttpHeaderSize="8192"
        emptySessionPath="true"
        scheme="https" secure="true" clientAuth="false"
        keystoreFile="${jboss.server.home.dir}/conf/chap8.keystore"
        keystorePass="changeit" sslProtocol = "TLS" />
  <!-- -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" address="${jboss.bind.address}" protocol="AJP/1.3"
         emptySessionPath="true" enableLookups="false" redirectPort="8443" />

      <Engine name="jboss.web" defaultHost="localhost">

         <!-- The JAAS based authentication and authorization realm implementation
         that is compatible with the jboss 3.2.x realm implementation.
         - certificatePrincipal : the class name of the
         org.jboss.security.auth.certs.CertificatePrincipal impl
         used for mapping X509[] cert chains to a Princpal.
         - allRolesMode : how to handle an auth-constraint with a role-name=*,
         one of strict, authOnly, strictAuthOnly
           + strict = Use the strict servlet spec interpretation which requires
           that the user have one of the web-app/security-role/role-name
           + authOnly = Allow any authenticated user
           + strictAuthOnly = Allow any authenticated user only if there are no
           web-app/security-roles
         -->
         <Realm className="org.jboss.web.tomcat.security.JBossSecurityMgrRealm"
            certificatePrincipal="org.jboss.security.auth.certs.SubjectDNMapping"
            allRolesMode="authOnly"
            />
         <!-- A subclass of JBossSecurityMgrRealm that uses the authentication
         behavior of JBossSecurityMgrRealm, but overrides the authorization
         checks to use JACC permissions with the current java.security.Policy
         to determine authorized access.
         - allRolesMode : how to handle an auth-constraint with a role-name=*,
         one of strict, authOnly, strictAuthOnly
           + strict = Use the strict servlet spec interpretation which requires
           that the user have one of the web-app/security-role/role-name
           + authOnly = Allow any authenticated user
           + strictAuthOnly = Allow any authenticated user only if there are no
           web-app/security-roles
         <Realm className="org.jboss.web.tomcat.security.JaccAuthorizationRealm"
            certificatePrincipal="org.jboss.security.auth.certs.SubjectDNMapping"
            allRolesMode="authOnly"
            />
         -->

        <Host name="localhost"
           autoDeploy="false" deployOnStartup="false" deployXML="false"
           configClass="org.jboss.web.tomcat.security.config.JBossContextConfig"
           >

            <!-- Uncomment to enable request dumper. This Valve "logs interesting 
                 contents from the specified Request (before processing) and the 
                 corresponding Response (after processing). It is especially useful 
                 in debugging problems related to headers and cookies."
            -->
            <!--
            <Valve className="org.apache.catalina.valves.RequestDumperValve" />
            -->
 
            <!-- Access logger -->
            <!--
            <Valve className="org.apache.catalina.valves.AccessLogValve"
                prefix="localhost_access_log." suffix=".log"
                pattern="common" directory="${jboss.server.home.dir}/log" 
                resolveHosts="false" />
            -->

            <!-- Uncomment to enable single sign-on across web apps
                deployed to this host. Does not provide SSO across a cluster.     
            
                If this valve is used, do not use the JBoss ClusteredSingleSignOn 
                valve shown below. 
                
                A new configuration attribute is available beginning with
                release 4.0.4:
                
                cookieDomain  configures the domain to which the SSO cookie
                              will be scoped (i.e. the set of hosts to
                              which the cookie will be presented).  By default
                              the cookie is scoped to "/", meaning the host
                              that presented it.  Set cookieDomain to a
                              wider domain (e.g. "xyz.com") to allow an SSO
                              to span more than one hostname.
             -->
            <!--
            <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
            -->

            <!-- Uncomment to enable single sign-on across web apps
               deployed to this host AND to all other hosts in the cluster.
            
               If this valve is used, do not use the standard Tomcat SingleSignOn
               valve shown above.
            
               Valve uses a JBossCache instance to support SSO credential 
               caching and replication across the cluster.  The JBossCache 
               instance must be configured separately.  By default, the valve 
               shares a JBossCache with the service that supports HttpSession 
               replication.  See the "jboss-web-cluster-service.xml" file in the 
               server/all/deploy directory for cache configuration details.
            
               Besides the attributes supported by the standard Tomcat
               SingleSignOn valve (see the Tomcat docs), this version also 
               supports the following attributes:
            
               cookieDomain   see above
            
               treeCacheName  JMX ObjectName of the JBossCache MBean used to 
                              support credential caching and replication across
                              the cluster. If not set, the default value is 
                              "jboss.cache:service=TomcatClusteringCache", the 
                              standard ObjectName of the JBossCache MBean used 
                              to support session replication.
            -->
            <!--
            <Valve className="org.jboss.web.tomcat.service.sso.ClusteredSingleSignOn" />
            -->
         
            <!-- Check for unclosed connections and transaction terminated checks
                 in servlets/jsps.
                 
                 Important: The dependency on the CachedConnectionManager
                 in META-INF/jboss-service.xml must be uncommented, too
            -->
            <Valve className="org.jboss.web.tomcat.service.jca.CachedConnectionValve"
                cachedConnectionManagerObjectName="jboss.jca:service=CachedConnectionManager"
                transactionManagerObjectName="jboss:service=TransactionManager" />

         </Host>

      </Engine>

   </Service>

</Server>



keystore лежит где положено, Catalina не возмущается...  smile 

Автор: hamsterKSU 23.8.2007, 17:03
моя рабочая конфигурация на 8443 порт
Код

 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
                keystoreFile="${jboss.server.home.dir}/conf/.keystore"
                keystorePass="123456"
               clientAuth="false" sslProtocol="TLS" />


Автор: Maverick 23.8.2007, 17:27
Заработало, всем спасибо... smile в особенности hamsterKSU... 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)