网络浪子 发表于 2015-11-14 10:30:54

小试tomcat基本安全认证

背景:tomcat-5.5.12设置为远程服务器 服务端设置: Step 1) 打开${tomcat_home}/conf/tomcat-users.xml加入如下代码:<role rolename=&quot;test&quot;/>
<user username=&quot;a&quot; password=&quot;b&quot; roles=&quot;test&quot;/>
Step2)修改web.xml<security-constraint>
            <display-name>Example Security Constraint</display-name>
            <web-resource-collection>
                <web-resource-name>Protected Area</web-resource-name>
                <!-- Define the context-relative URL(s) to be protected -->
                <url-pattern>/test/*</url-pattern>
                <!-- If you list http methods, only those methods are protected -->
                <http-method>DELETE</http-method>
                <http-method>GET</http-method>
                <http-method>POST</http-method>
                <http-method>PUT</http-method>
            </web-resource-collection>
            <auth-constraint>
                <!-- Anyone with one of the listed roles may access this area -->
                <role-name>test</role-name>
            </auth-constraint>
      </security-constraint>
   
      <!-- Default login configuration uses BASIC authentication -->
      <login-config>
            <auth-method>BASIC</auth-method>
            <realm-name>WebService Form-Based Authentication Area</realm-name>

</login-config> 对网站/test/下的任何请求采用基本安全认证 客户端编程:客户端通过httpclient-2.0.2请求该url,方法如下: HttpClient httpClient = new HttpClient();

Credentials defaultcreds = new UsernamePasswordCredentials(&quot;a&quot;, &quot;b&quot;);
httpClient.getState().setCredentials(&quot;WebService Form-Based Authentication Area&quot;,&quot;www.cat.cn&quot;,defaultcreds);

String url = &quot;http://www.cat.cn/test/index.do&quot;;

GetMethod method = new GetMethod(url);

method.setDoAuthentication( true );

httpClient.executeMethod(method);

String s = method.getResponseBodyAsString();

System.out.println(s);
             版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: 小试tomcat基本安全认证