9 Replies Latest reply on Feb 5, 2016 11:58 AM by tadayosi

    How to allow CORS

    scisci

      Hi,

      I've a service bean with a rest binding, is it possible allow cross orignin resource sharing?

      How to add need headers on http response?

      Thanks

      Mirko

        • 1. Re: How to allow CORS
          arteme

          Hi,

           

          You'd want to add something like an "Access-Control-Allow-Origin: *" header, right?

           

          RESTEasy context mapper (like HTTP context mapper) will take any property from the context with HTTP endpoint label on it and promote it to a HTTP header on the reply. So you need to do something like this:

          context.setProperty("Access-Control-Allow-Origin", "*").addLabels(new String[]{ EndpointLabel.HTTP.label() });

           

          -A

          • 2. Re: How to allow CORS
            scisci

            Hi Artem,

            I've tryed what you suggested but didn't work, no header was added

             

            In my ServiceBean implementation 've added

            @Inject private Context context;

            and before return I've added you code.

            I've also tryed to add  the scope ( I've read the document of context mapping but I think is outdated, On version 1.1.0 there are only EXCANGE e MESSAGE scope ). by deafult is MESSAGE

             

            Is there any other suggestion ?

             

            Thanks

            Mirko

            • 3. Re: How to allow CORS
              trohovsky

              Setting of headers on a response is a bit tricky in a bean component. Try to use the following code:

               

              @Inject

              Exchange exchange;

               

              public String greet(String name) {

                   Message message = exchange.createMessage();

                   message.setContent("Hello " + name);

                   message.getContext().setProperty("Access-Control-Allow-Origin", "*");

                   exchange.send(message);

                   return null;

              }

               

              Tomas

              • 4. Re: How to allow CORS
                scisci

                Hi,

                I've tried to inject exchange but there was an error of Nullpoint Exception at run time.

                I've tried another solution , I've used ExchangeInterception

                 

                @Named("AllowCORS")

                public class DealsInterceptor implements ExchangeInterceptor {

                 

                  @Override

                     public void before(String target, Exchange exchange) throws HandlerException {

                         // Not interested in doing anything before the provider is invoked

                     }

                 

                     @Override

                     public void after(String target, Exchange exchange) throws HandlerException {

                         if (exchange.getProvider().getName().getLocalPart().equals("ContabilizzazioneService") && ExchangeState.OK.equals(exchange.getState()))

                         {

                       

                          Context context = exchange.getContext();

                          context.setProperty("Access-Control-Allow-Origin", "*").addLabels(new String[]{ EndpointLabel.HTTP.label() });

                         }

                     }

                     @Override

                     public List<String> getTargets() {

                        return Arrays.asList(PROVIDER);

                     }

                }

                 

                This solution add the property on exchange.context.

                I've also replace deafault ContextMapper with this:

                 

                @Override

                  public void mapFrom(RESTEasyBindingData source, Context context) throws Exception

                  {

                  super.mapFrom(source, context);

                  }

                 

                 

                  @Override

                  public void mapTo(Context context, RESTEasyBindingData target) throws Exception

                  {

                 

                  //super.mapTo(context, target);

                  Map<String, List<String>> httpHeaders = target.getHeaders();

                        for (Property property : context.getProperties())

                        {

                            String name = property.getName();

                            Object value = property.getValue();

                          

                            //LOGGER.info("Property name : " + name + " value : " + value.toString());

                          

                            if ((value != null) && (matches(name) || property.hasLabel(EndpointLabel.HTTP.label())))

                            {

                         

                //             LOGGER.info("Property name : " + name + " value : " + value.toString());

                         

                                if (HTTP_RESPONSE_STATUS.equals(name))

                                {

                                    target.setStatusCode((Integer)property.getValue());

                                }

                                else

                                {

                                    if (value instanceof List)

                                    {

                                        List<String> stringList = new ArrayList<String>();

                                        for (Object obj : ((List)value))

                                        {

                                            if (obj != null)

                                            {

                                                stringList.add(obj.toString());

                                            }

                                            else

                                            {

                                                stringList.add(null);

                                            }

                                        }

                                        httpHeaders.put(name, stringList);

                                    }

                                    else if (value instanceof String)

                                    {

                                        List<String> list = new ArrayList<String>();

                                        list.add(String.valueOf(value));

                                        httpHeaders.put(name, list);

                                    }

                                }

                            }

                        }

                 

                        LOGGER.info("Access-Control-Allow-Origin : " + httpHeaders.get("Access-Control-Allow-Origin").toString());

                 

                  }

                 

                and the property was added to HttpHeaders.

                 

                But at http response on client there isn't the header Access-Control-Allow Origin

                 

                is there anyone help me?

                Where am I doing wrong ?

                 

                Thanks

                Mirko

                • 5. Re: How to allow CORS
                  trohovsky

                  I would definitely go the Exchange injection way. It works well for me. Are you sure you imported org.switchyard.Exchange and not org.apache.camel.Exchange? Maybe setting of  <contextMapper includes=".*"> in the binding may solve your issue.

                  • 6. Re: How to allow CORS
                    tadayosi

                    For anyone who is interested, I created a working example project for enabling CORS in SwitchYard here:

                    samples-switchyard/rest-cors at master · tadayosi/samples-switchyard · GitHub

                    • 7. Re: How to allow CORS
                      tadayosi

                      As it turned out, none of these approaches discussed here can support CORS preflight requests yet. So I filed a RFE to address it:

                      [SWITCHYARD-2460] Support CORS for RESTEasy binding - JBoss Issue Tracker

                      • 8. Re: How to allow CORS
                        ramandeep

                        Hi Mirko ,

                         

                        I have a similar requirement , I have a switchyard project where I am exposing rest services

                        is it possible allow cross orignin resource sharing?How to add need headers on http response?

                        what was the solution you found for this Issue ? Many thanks in advance

                         

                         

                        Regards,

                        Ramandeep

                        • 9. Re: How to allow CORS
                          tadayosi