Search code examples
spring-bootcorscxf

CXF 3.2.2 CORS failed with "No 'Access-Control-Allow-Origin' header is present"


I was developing a Restful service using CXF + spring boot. and had problems with CORS setting

I set CORS on service definition interface (GateRs)

...
@Service
@CrossOriginResourceSharing(
    allowAllOrigins = true, 
    allowHeaders = {
            "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Datetime", 
            "Accept-Language", "Authorization", "Content-Language", "Content-Length", 
            "Content-Type", "Origin", "User-Agent"},
    exposeHeaders = {
            "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Datetime", 
            "Accept-Language", "Authorization", "Content-Language", "Content-Length", 
            "Content-Type", "Origin", "User-Agent"},
    allowCredentials = true, 
    maxAge = 1209600 )
public interface GateRs {

    @POST
    @Path("/require")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @VoluntarySecure
    public Res require(Req req);    
...

implement interface with a class

@Component
public class Gate implements GateRs {   

        @Override
        public Res require(Req req) { 
...

attach the 'CrossOriginResourceSharingFilter' to the service bean

    @Bean
        public CrossOriginResourceSharingFilter cors() {
            return new CrossOriginResourceSharingFilter();
        }

    @Bean(destroyMethod = "destroy") @DependsOn(Bus.DEFAULT_BUS_ID)
    public Server jaxRsServer() {
        final JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();

        factory.setServiceBean(new Gate());
        factory.setProviders(Arrays.asList(jackson(), cors()));
        factory.setBus(springBus());
        factory.setAddress("/Gate");

        return factory.create();
    } 
...

the client is a mobile application based on Ionic, and emulated by Chrome browser.

the '/Gate/require' returned '404' becasue CORS failed with no " Access-Control-Allow-Origin" header.

I looked into the detail; and found out that the preflight ('OPTIONS') actually succeed; the "POST" failed, triggered the above mentioned messages

the preflight(OPTIONS)

enter image description here

the POST failed; it appears that the server side had not presented 'Access-Control-Allow-Origin' header in the response message enter image description here

does anyone has any idea or suggestion?

thanks


Solution

  • I finally solved the problem by changing the '@CrossOriginResourceSharing' as follows:

    ...
    @CrossOriginResourceSharing(
        allowAllOrigins = true,
        allowCredentials = true, 
        maxAge = 1209600 )
    public interface GateRs {
    ...