菜单

Tomcat htaccess

2015年12月22日 - Java

Protecting a Resource with a MemoryRealm

To actually see how a MemoryRealm works, let’s create a realm that protects a sample web application named /onjava. At this point, if you have not already done so, take a look at my previous OnJava article, Deploying Web Applications to Tomcat. We will be using the /onjava web application from it. The steps involved in setting up a new MemoryRealm are described in the following list.

  1. Open <tomcat_home>/conf/server.xml and uncomment the following line.

    <Realm className="org.apache.catalina.realm.MemoryRealm" />

    By un-commenting this <realm> entry, you are making the MemoryRealm the default realm implementation for the entire default container. If you cannot find this entry, add it directly under the Engine sub-element.

  2. Open <tomcat_home>/webapps/onjava/WEB-INF/web.xml and add the following security constraint:

    <security-constraint>
    <web-resource-collection>
    <web-resource-name>OnJava Application</web-resource-name>
    <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
    <role-name>onjavauser</role-name>
    </auth-constraint>
    </security-constraint>

    There are only two sub-elements that you need to focus upon. The first is the <url-pattern> sub-element. This sub-element defines the URL pattern that will be protected by the resource. The entry you included protects the entire /onjava Web application. The second sub-element, <role-name>, defines the user role that can access the resource protected by the previously defined <url-pattern>. In summary, this entire entry states that the/onjava Web application can only be accessed by users with a defined role of onjavauser.

  3. Add the following <login-config> sub-element directly following the <security-constraint>.

    <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>OnJava Application</realm-name>
    </login-config>

    The <login-config> sub-element defines the authentication method for the defined realm. The possible values are BASIC, DIGEST, and FORM. And the <realm-name> sub-element names the Web resource that this<login-config> maps to.

  4. Open <tomcat_root>/conf/tomcat-users.xml and add the following <user> sub-element:

    <user name="bob" password="password" roles="onjavauser" />

    The <user> sub-element you are adding will create a new user in the MemoryRealm database with a name of bob, a password of password, and a role of onjavauser. You should notice that the value of the roles attribute matches the value of the <role-name> sub-element of the previously-defined <security-contstraint>.

  5. To complete this configuration, stop and restart the Tomcat server.

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注