Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a secure Web Service in Apache CXF

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people don't know what to do about how to create a secure Web Service in Apache CXF. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

In the process of using Web Service, we need to authenticate web service requests in many cases. For applications running in web containers, it may be easier to do some processing through filter, but in fact, CXF itself also provides a way to authenticate web service. Let's take a look at how to implement it.

1. The first is a simple pojo

Package com.googlecode.garbagecan.cxfstudy.security; public class User {private String id; private String name; private String password; public String getId () {return id;} public void setId (String id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name } public String getPassword () {return password;} public void setPassword (String password) {this.password = password;}}

2. Web Service interface

Package com.googlecode.garbagecan.cxfstudy.security; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebResult; import javax.jws.WebService; @ WebService public interface UserService {@ WebMethod @ WebResult List list ();

3. Web Service implementation class

Package com.googlecode.garbagecan.cxfstudy.security; import java.util.ArrayList; import java.util.List; public class UserServiceImpl implements UserService {public List list () {List users = new ArrayList (); for (int I = 0; I < 10; iTunes +) {User user = new User (); user.setId ("" + I); user.setName ("user_" + I) User.setPassword ("password_" + I); users.add (user);} return users;}}

4. Handler on Server, in which a Map is used to store user information. You can really use database or other methods to obtain users and passwords in an application.

Package com.googlecode.garbagecan.cxfstudy.security; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.ws.security.WSPasswordCallback; public class ServerUsernamePasswordHandler implements CallbackHandler {/ / key is username, value is password private Map users; public ServerUsernamePasswordHandler () {users = new HashMap () Users.put ("admin", "admin");} public void handle (Callback [] callbacks) throws IOException, UnsupportedCallbackException {WSPasswordCallback callback = (WSPasswordCallback) callbacks [0]; String id = callback.getIdentifier () If (users.containsKey (id)) {if (! callback.getPassword (). Equals (users.get (id) {throw new SecurityException ("Incorrect password.");}} else {throw new SecurityException ("Invalid user.");}

5. Handler on Client, which is used to set the user password. In real applications, the user name and password can be changed logically according to this class and the following test class.

Package com.googlecode.garbagecan.cxfstudy.security; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.ws.security.WSPasswordCallback; public class ClientUsernamePasswordHandler implements CallbackHandler {public void handle (Callback [] callbacks) throws IOException, UnsupportedCallbackException {WSPasswordCallback callback = (WSPasswordCallback) callbacks [0]; int usage = callback.getUsage () System.out.println ("identifier:" + callback.getIdentifier ()); System.out.println ("usage:" + callback.getUsage ()); if (usage = = WSPasswordCallback.USERNAME_TOKEN) {callback.setPassword ("admin");}

6. Unit test class, notice that WSS4JInInterceptor is added to the Interceptor list on the Server side, and WSS4JOutInterceptor is added to the Interceptor list on Client.

Package com.googlecode.garbagecan.cxfstudy.security; import java.net.SocketTimeoutException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.ws.WebServiceException; import junit.framework.Assert; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor Import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor; import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor; import org.apache.ws.security.WSConstants; import org.apache.ws.security.handler.WSHandlerConstants; import org.junit.BeforeClass; import org.junit.Test Public class UserServiceTest {private static final String address = "http://localhost:9000/ws/security/userService"; @ BeforeClass public static void setUpBeforeClass () throws Exception {JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean (); factoryBean.getInInterceptors () .add (new LoggingInInterceptor ()); factoryBean.getOutInterceptors () .add (new LoggingOutInterceptor ()); Map props = new HashMap (); props.put (" action "," UsernameToken ") Props.put ("passwordType", "PasswordText"); props.put ("passwordCallbackClass", ServerUsernamePasswordHandler.class.getName ()); WSS4JInInterceptor wss4JInInterceptor = new WSS4JInInterceptor (props); factoryBean.getInInterceptors (). Add (wss4JInInterceptor); factoryBean.setServiceClass (UserServiceImpl.class); factoryBean.setAddress (address); factoryBean.create () } @ Test public void testList () {JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean (); factoryBean.setAddress (address); factoryBean.setServiceClass (UserService.class); Object obj = factoryBean.create (); Client client = ClientProxy.getClient (obj); Endpoint endpoint = client.getEndpoint (); Map props = new HashMap () Props.put (WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); props.put (WSHandlerConstants.USER, "admin"); props.put (WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT); props.put (WSHandlerConstants.PW_CALLBACK_CLASS, ClientUsernamePasswordHandler.class.getName ()); WSS4JOutInterceptor wss4JOutInterceptor = new WSS4JOutInterceptor (props); endpoint.getOutInterceptors () .add (wss4JOutInterceptor) HTTPConduit conduit = (HTTPConduit) client.getConduit (); HTTPClientPolicy policy = new HTTPClientPolicy (); policy.setConnectionTimeout (5 * 1000); policy.setReceiveTimeout (5 * 1000); conduit.setClient (policy); UserService service = (UserService) obj; try {List users = service.list (); Assert.assertNotNull (users) Assert.assertEquals (10, users.size ());} catch (Exception e) {if (e instanceof WebServiceException & & e.getCause () instanceof SocketTimeoutException) {System.err.println ("This is timeout exception.");} else {e.printStackTrace () }}

* run the above test class to test the results, or you can change the password in the test method to see the error results. Here, you will not write the test case for the wrong password.

After reading the above, have you mastered how to create a secure Web Service in Apache CXF? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report