webservice tomcat7.0.27 基本用户认证配置
1.tomcat-users.xml文件xml元素tomcat-users中间配置访问的角色和用户如下:
<role rolename="webservice"/>
<user username="webservice_user" password="webservice_user" roles="webservice"/>
2.hysh web项目配置文件web.xml配置如下片段
<security-constraint>
?<web-resource-collection>
??<web-resource-name>secured services</web-resource-name>
??<url-pattern>/services/*</url-pattern>
?</web-resource-collection>
?<auth-constraint>
??<role-name>webservice</role-name>
?</auth-constraint>
</security-constraint>
<login-config>
?<auth-method>BASIC</auth-method>
?<realm-name>webservice</realm-name>
</login-config>
3.web浏览器输入符合url-pattern对应路径时会弹出登录认证对话框,输入tomcat-users.xml文件中设置的username,password便能正常显示。
路径如:http://www.helloworlddemo.com:8080/test/services/WebService?wsdl。
如输入的username,password不正确,将不能登录。
4.Axis2 webservice客户端调用代码加入基本验证
ServiceClient client = null;
Options options = null;
OMElement response = null;
Authenticator authenticator = null;
authenticator = new Authenticator();
List<String> auth = new ArrayList<String>();
auth.add(Authenticator.BASIC);
authenticator.setAuthSchemes(auth);
// Add user creadentials to the transport header
authenticator.setUsername("webservice_user");
authenticator.setPassword("webservice_user");
authenticator.setRealm("webservice");
authenticator.setPreemptiveAuthentication(true);
options.setProperty(HTTPConstants.AUTHENTICATE,authenticator);
client.setOptions(options);
如果没有加入options.setProperty(HTTPConstants.AUTHENTICATE,authenticator); 代码访问将会抛出异常如下: ?Exception in thread "main" org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized