Hi, sorry missed it, if you work with JAX-RS 2.0 filters then you should get Authorization header from ContainerRequestContainer and parse it manually. The CXF specific approach is handy indeed though, PhaseInterceptorChain won't be changed AFAIK

Sergey

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;

import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;

public class AuthFilter implements ContainerRequestFilter {

@Override
public void filter(ContainerRequestContext req) throws IOException {
System.err.println("filter!");
Message message = PhaseInterceptorChain.getCurrentMessage();
         AuthorizationPolicy policy = 
(AuthorizationPolicy)message.get(AuthorizationPolicy.class);

         if (policy==null){
         req.abortWith(Response.status(401).header("WWW-Authenticate", "Basic 
realm=\"PTServer\"").build());
         return;
         }
         String username = policy.getUserName();
         String password = policy.getPassword();
         if ("demo".equals(password)&&"demo".equals(username)) {
         return;
         }
         else{
         req.abortWith(Response.status(401).header("WWW-Authenticate", "Basic 
realm=\"PTServer\"").build());
         }

}

}

then, in the class that extends javax.ws.rs.core.Application, overwrite
public Set<Class<?>> getClasses()

@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(AuthFilter.class);

return classes;
}

My further question is: is it safe to use 
PhaseInterceptorChain.getCurrentMessage()? Will this API be changed in the 
future? Is it OK to use this method inside those Jax-rs service method?



Abhijit Sarkar <[email protected]> 于 2014年4月1日, 星期二, 1:43 下午 写道:

Kevin,I had written some code without Spring but JAX-WS, not JAX-RS. If you 
want to take a look, here it is.
https://github.com/abhijitsarkar/java-ee/tree/master/webservices/jax-ws/jaxws-instrumentation
Best,Abhijit Sarkar

Date: Mon, 31 Mar 2014 21:29:05 +0800
From: [email protected]
Subject: 回复: How to configure CXF Jas-RS to use RequestHandler without spring
To: [email protected]

Sorry, I mean how to config CXF Jax-rs to use RequestHandler (Filter) to 
implement Basic Authentication without Spring.  Thanks


Kevin Cai <[email protected]> 于 2014年3月31日, 星期一, 9:26 下午 写道:

Dear all,

Seems that all config docs of CXF are all about config cxf with Spring.  I 
would like to know how to config CXF Jax-rs to use RequestHandler (Filter) to 
implement Basic Authentication.  Thanks.


Yours,
Kevin Choi

Reply via email to