webservice tomcat7.0.27 基本用戶認證配置及客戶端代碼調用

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章