糯米文學吧

位置:首頁 > IT認證 > J2EE

如何創建安全的Web Service

J2EE3.08W

我們在使用web Service的`過程中,很多情況是需要對web service請求做認證的,對於運行在web容器裏的應用程序來説,可能會比較簡單一些,通常可以通過filter來做一些處理,但是其實CXF本身也提供了對web service認證的方式。

如何創建安全的Web Service

  1. 首先是一個簡單pojo

package rity;

public class User {

private String id;

private String name;

private String password;

public String getId() {

return id;

}

public void setId(String id) {

= id;

}

public String getName() {

return name;

}

public void setName(String name) {

= name;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

word = password;

}

}

  2. Web Service接口

package rity;

import ;

import ethod;

import esult;

import ervice;

@WebService

public interface UserService {

@WebMethod

@WebResult List list();

}

  3. Web Service實現類

package rity;

import yList;

import ;

public class UserServiceImpl implements UserService {

public List list() {

List users = new ArrayList();

for (int i = 0; i < 10; i++) {

User user = new User();

d("" + i);

ame("user_" + i);

assword("password_" + i);

(user);

}

return users;

}

}

  4. Server端Handler,其中使用了一個Map來存放用户信息,真是應用中可以使用數據庫或者其它方式獲取用户和密碼

package rity;

import ception;

import Map;

import ;

import back;

import backHandler;

import pportedCALlbackException;

import sswordCallback;

public class ServerUsernamePasswordHandler implements CallbackHandler {

// key is username, value is password

private Map users;

public ServerUsernamePasswordHandler() {

users = new HashMap();

("admin", "admin");

}

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

WSPasswordCallback callback = (WSPasswordCallback) callbacks[0];

String id = dentifier();

if (ainsKey(id)) {

if (!assword()ls((id))) {

throw new SecurityException("Incorrect password.");

}

} else {

throw new SecurityException("Invalid user.");

}

}

}

  5. Client端Handler,用來設置用户密碼,在真實應用中可以根據此類和下面的測試類來修改邏輯設置用户名和密碼。

package rity;

import ception;

import back;

import backHandler;

import pportedCallbackException;

import sswordCallback;

public class ClientUsernamePasswordHandler implements CallbackHandler {

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

WSPasswordCallback callback = (WSPasswordCallback) callbacks[0];

int usage = sage();

tln("identifier: " + dentifier());

tln("usage: " + sage());

if (usage == NAME_TOKEN) {

assword("admin");

}

}

}

  6. 單元測試類,注意在Server端添加了WSS4JInInterceptor到Interceptor列表中,在Client添加了WSS4JOutInterceptor到Interceptor列表中。

package rity;

import etTimeoutException;

import Map;

import ;

import ;

import erviceException;

import rt;

import nt;

import oint;

import ntProxy;

import ingInInterceptor;

import ingOutInterceptor;

import sProxyFactoryBean;

import sServerFactoryBean;

import Conduit;

import ClientPolicy;

import 4JInInterceptor;

import 4JOutInterceptor;

import nstants;

import ndlerConstants;

import reClass;

import ;

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();

nInterceptors()(new LoggingInInterceptor());

utInterceptors()(new LoggingOutInterceptor());

Map props = new HashMap();

("action", "UsernameToken");

("passwordType", "PasswordText");

("passwordCallbackClass", ame());

WSS4JInInterceptor wss4JInInterceptor = new WSS4JInInterceptor(props);

nInterceptors()(wss4JInInterceptor);

erviceClass(s);

ddress(address);

te();

}

@Test

public void testList() {

JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();

ddress(address);

erviceClass(s);

Object obj = te();

Client client = lient(obj);

Endpoint endpoint = ndpoint();

Map props = new HashMap();

(ON, NAME_TOKEN);

(, "admin");

(WORD_TYPE, _TEXT);

(_CALLBACK_CLASS, ame());

WSS4JOutInterceptor wss4JOutInterceptor = new WSS4JOutInterceptor(props);

utInterceptors()(wss4JOutInterceptor);

HTTPConduit conduit = (HTTPConduit) onduit();

HTTPClientPolicy policy = new HTTPClientPolicy();

onnectionTimeout(5 * 1000);

eceiveTimeout(5 * 1000);

lient(policy);

UserService service = (UserService) obj;

try {

List users = ();

rtNotNull(users);

rtEquals(10, ());

} catch(Exception e) {

if (e instanceof WebServiceException

&& ause() instanceof SocketTimeoutException) {

tln("This is timeout exception.");

} else {

tStackTrace();

}

}

}

}

最後運行上面的測試類來測試結果,也可以修改測試方法中的密碼,看看錯誤結果。

標籤:web SERVICE