微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 CXF

如何解决使用 CXF

我需要将服务 bean 中的调用包装在自定义安全上下文中。为了稍微解耦所有内容,我不想将每个方法都包装在 Subject.doAs() 中,而是更愿意找到允许我使用拦截器从请求标头读取信息并包装后续调用方法

我尝试实现一个 ContainerRequestFilter 来做到这一点。看看 JAASAuthenticationFilter 是如何工作的,我认为应该是这样的:

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MultivaluedMap<String,String> headers = requestContext.getHeaders();
    Subject subject = getSubjectFromHeader(headers);
    
    // Reject request if header is missing
    if(subject == null) {
        requestContext.abortWith(Response.status(Status.BAD_REQUEST).entity("Missing header:" + HEADER_SUBJECT).build());
        return;
    }
    
    // Wrap the remaining chain is security context
    Message message = JAXRSUtils.getCurrentMessage();
    Subject.doAs(subject,new PrivilegedAction<Void>() {
           @Override
           public Void run() {
               InterceptorChain chain = message.getInterceptorChain();                
               if (chain != null) {
                   chain.doIntercept(message);
               }
               return null;
           }
       });
}

不幸的是,这似乎不适用于 JAX-RS 服务。调试问题,好像在使用我的RequestFilter时,调用service方法时没有提取和提供Path和Query参数,然后失败:

org.apache.cxf.interceptor.Fault: wrong number of arguments while invoking public a.b.c.dtos.TodoOutDTO ch.suisa.todo.rs.impl.TodoRestServiceImpl.getTodo(java.lang.Long,java.lang.String) with params null.
    at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:167)[74:org.apache.cxf.cxf-core:3.0.4.redhat-621084]
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:141)[74:org.apache.cxf.cxf-core:3.0.4.redhat-621084]
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:200)[103:org.apache.cxf.cxf-rt-frontend-jaxrs:3.0.4.redhat-621084]
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:99)[103:org.apache.cxf.cxf-rt-frontend-jaxrs:3.0.4.redhat-621084]
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)[74:org.apache.cxf.cxf-core:3.0.4.redhat-621084]
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)[74:org.apache.cxf.cxf-core:3.0.4.redhat-621084]
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)[74:org.apache.cxf.cxf-core:3.0.4.redhat-621084]
    at ch.suisa.todo.rs.SecurityHeaderInterceptor$2.run(SecurityHeaderInterceptor.java:97)[409:phx-todo-rs:5.0.0.SNAPSHOT]
    at ch.suisa.todo.rs.SecurityHeaderInterceptor$2.run(SecurityHeaderInterceptor.java:1)[409:phx-todo-rs:5.0.0.SNAPSHOT]
    at java.security.AccessController.doPrivileged(Native Method)[:1.8.0_265]
    at javax.security.auth.Subject.doAs(Subject.java:360)[:1.8.0_265]

这是一个错误还是无法按预期工作的东西?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。