Kumar
Kumar

Reputation: 961

Jquery call of Java RESTful service not working CORS

I have one rest service deployed on Tomcat 7 and running. I can get the response data through browser, but when I tried it through jQuery it is showing an error. Please Check the snapshot.

@Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) req;
        HttpServletResponse httpRes = (HttpServletResponse) res;

        //System.out.println("Client Ip is : "+ SecurityFilter.getClientIpAddr(httpReq));

        String domain = new URL(httpReq.getRequestURL().toString()).getHost();
        //System.out.println("Domain is " + domain);

        // referrer
        String referrer = httpReq.getHeader("referer");
        //System.out.println("Referral URL is -" + referrer);

        // Security Key
        String securityKey = httpReq.getParameter("secKey");
        //System.out.println("Security Key Parameter " + securityKey);

        // Origin
        // No Origin header present means this is not a cross-domain request
        String clientOrigin = httpReq.getHeader("Origin");
        //System.out.println("Origin of the Request " + clientOrigin);

        // CORS implementation
        httpRes.addHeader("Access-Control-Allow-Origin", "*");
        httpRes.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        // httpRes.addHeader("Access-Control-Allow-Origin", clientOrigin);

        if ("OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
            httpRes.addHeader("Access-Control-Allow-Credentials", "true");
        }

        ValidateClient vl = new ValidateClient();

        String secKey = "fmg_seckey"; //"SEC_1";;
        String clientUrl = "fmggroup.com";//"www.xyzclient1.com";

        // if request is coming from third party. Referral will be null if all
        // request is from same server.

        if  (referrer != null) {
            clientUrl = referrer.split("/")[2];
            secKey = securityKey;
        }

        //System.out.println("Security Key " + secKey);
        //System.out.println("Domain Name for the client " + clientUrl);


        if (vl.isValidClient(secKey, clientUrl)) {
            // httpReq.getRequestDispatcher("/intellixservices/activetime").forward(httpReq,httpRes);
            chain.doFilter(httpReq, httpRes);
        } else {

            httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Not Authorised");
            // httpReq.getRequestDispatcher("/intellixservices/exception").forward(httpReq,
            // httpRes);

        }

    }

in the resource class:

// CORS implementation
private String corsHeaders;

private Response makeCORS(ResponseBuilder responseBuilder, String returnMethod) {
    ResponseBuilder rb = responseBuilder.header("Access-Control-Allow-Origin", "*")
       .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

    if (!"".equals(returnMethod)) {
       rb.header("Access-Control-Allow-Headers", returnMethod);
    }
    return rb.build();
 }

 private Response makeCORS(ResponseBuilder responseBuilder) {
    return makeCORS(responseBuilder, corsHeaders);
 }

 @OPTIONS
 public Response getEmployee(@HeaderParam("Access-Control-Request-Headers") String request) {
     corsHeaders = request;
     return makeCORS(Response.ok(), request);
 }

and then returning

Response response = Response.status(404).build();

if (mf != null) {
             response = makeCORS(Response.status(200).entity(mf));
         } else {
             response = makeCORS(Response.status(500));
         }

         return response;

I am unable to resolve it. Please suggest.

enter image description here

This is my jQuery Call :-

<html>
   <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <script type="application/javascript">      
         (function($) {
            var url = 'http://localhost:8888/IntellixWebApi/intellixservices/dnareport/MTk3MC0wOS0wNFQwNjowNTowMA==/NDEuNTU4MTUyNSA=/LTczLjA1MTQ5NjYg/QW1lcmljYS9OZXdfWW9yaw==/MTpBOjB8QToxOjF8MToxOjE=/json';

            $.ajax({
               type: 'GET',
               url: url,
               async: true,
               contentType: 'application/json',
               success: function(response) {
                  alert("success");
               },
               error: function(xhr) {
                  alert('Error!  Status = ' + xhr.status + " Message = " + xhr.statusText);
               }
            });
         })(jQuery);
      </script>
   </head>
   <body>
      <!-- we will add our HTML content here -->
   </body>
</html>

Upvotes: 1

Views: 3662

Answers (2)

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

The following can be added to the Response and it can prevent CORS issues:

Response.status(200)
            .header("Access-Control-Allow-Origin", request.getHeader("Origin"))
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Credentials", "true")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "1209600")
            .entity(applicationSyncService.buildApplicationData())
            .build();

Response is of type : HttpServletRequest. It can be a security breach though.

You can make the call from jquery like this:

$.ajax({

    xhrFields: {
    withCredentials: true
},
    type: 'GET',
    url: server + '/hello',
    dataType: 'json',
    async: true,
    success: function(data){

        if(data.connected){
            //your code
    },
    error: function(a, b, c){

    }
});

This is a much simpler solution without the use of filters.

Upvotes: 0

Kumar
Kumar

Reputation: 961

Any way I resolved the issue after a lot of googling. I added CORS filter and java utility jar filter and some configuration changes in the web.xml. These links are very helpful

Link 1

Link 2

Thanks you all for this great help.

Upvotes: 3

Related Questions