小编Hak*_*man的帖子

在Apache CXF Interceptor中编写消息内容和响应代码

我试图通过使其中一个方法需要HTTP基本身份验证来确保我的Web服务安全.为了做到这一点,我实现了一个自定义的Interceptor调用LoginInterceptor,它检查请求的URL,如果它对应于一个被调用的方法open,它会检查消息头是否有用户名和密码.

如果标头中没有验证字段,则响应代码设置为HTTP_UNAUTHORIZED,如果用户名或密码不正确,则将响应代码设置为HTTP_FORBIDDEN.这是代码:

public LoginInterceptor() {
     super(Phase.RECEIVE);
     addAfter(RequestInterceptor.class.getName()); //another custom interceptor, for some simple redirections.
}

public void handleMessage(Message message) throws Fault {
     String requestURI = message.get(Message.REQUEST_URI).toString();
     String methodKeyword = requestURI.substring("localhost".length()+1).split("/")[0];

     if(methodKeyword.equals("open")) {
          AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
          if(policy == null) {
              sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
              return;
          }

          //userPasswords is a hashmap of usernames and passwords.     
          String realPassword = userPasswords.get(policy.getUserName());
          if (realPassword == null || !realPassword.equals(policy.getPassword())) {
                    sendErrorResponse(message, HttpURLConnection.HTTP_FORBIDDEN);
          }
     }
}

//This is where the …
Run Code Online (Sandbox Code Playgroud)

java web-services cxf jax-rs

4
推荐指数
1
解决办法
3193
查看次数

标签 统计

cxf ×1

java ×1

jax-rs ×1

web-services ×1