5
votes

Using angular and Spring Boot we're trying to add authentication to our service but for some reason we can't 'open' and fetch data from an url we know works

Angular:

this.getMismatches = function () {
    return $http({
            "async": true,
            "crossDomain": true,
            "url": GLOBALS.mismatchUrl,
            "method": "GET",
            "headers": {
                "authorization": "Basic YWRtaW46USNROawdNmY3UWhxQDlQA1VoKzU="
        }
    });
}

(currently the login token is hard coded for testing purposes)

Rest service:

@CrossOrigin(origins = "*")
@RequestMapping("/api/mismatch")
public List<Mismatch> home() {
    return service.getAll();
}

CrossOrigin = * should take care of the CORS issue but this failed URL call is really weird.

Extra things we've tried:

'Access-Control-Allow-Methods', 'GET, POST, OPTIONS'
'Access-Control-Allow-Origin', '*'
'Content-Type', json plaintext jsonp etc

App.js:
    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
1
What's GLOBALS.mismatchUrl set to? I'd imagine it doesn't say "Invalid URL" for no reason at all...Brother Woodrow
My bad, posted the wrong error message.Laurens
can you get response in postman?bipin patel
Yeah, that's the weird part.Laurens
can you give 'GLOBALS.mismatchUrl' value?bipin patel

1 Answers

12
votes

You have mentioned in your comments that by using postman you can get the response as expected. That is a good starting point. I suspect that by using the curl command curl -i -X URL from the terminal also returns the correct response.

If postman works correctly, you have to be aware by the fact that right before making a request angular sends another request, called pre-flight request, which does a minimal check to the endpoint at the server side.

This request is an OPTIONS type request.

First, you have to make sure that your dispatcherServlet accepts OPTIONS requests. You can achieve this either by specifying it in a *.properties configuration file , such as:

spring.mvc.dispatch-options-request=true

or by configuring web.xml

<servlet>
    <!--content eluded for clarity-->
    <init-param>
        <param-name>dispatchOptionsRequest</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

After you have configured it to accept OPTIONS requests, create a Filter.java and configure a CORS filter.

You can guide by the following example:

public class CorsFilter implements Filter{

@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain filterChain) throws IOException, ServletException {

    if(response instanceof HttpServletResponse){
        HttpServletResponse alteredResponse = ((HttpServletResponse)response);
        addCorsHeader(alteredResponse);
    }

    filterChain.doFilter(request, response);
}

private void addCorsHeader(HttpServletResponse response){
    //TODO: externalize the Allow-Origin
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
    response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
    response.addHeader("Access-Control-Max-Age", "1728000");
}

@Override
public void destroy() {}

@Override
public void init(FilterConfig filterConfig)throws ServletException{}
}

In the end, don't forget to add this filter in web.xml along with the following init-params.

<filter>
    <filter-name>cors-filter</filter-name>
    <filter-class>ai.surge.usrmngmtservice.util.cors.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Authorization,Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <!--<init-param>-->
        <!--<param-name>cors.preflight.maxage</param-name>-->
        <!--<param-value>1800</param-value>-->
    <!--</init-param>-->
</filter>

You should be ready to go now.