Search code examples
javaspringcorscross-domainsame-origin-policy

Browser not showing valid response for cross-origin request


I made a cross origin request. Browser shows correct message on the console but also shows reponse in the network tab (which should not have been shown).

Message on the console: enter image description here

enter image description here

Message shown under response of network tab:

enter image description here enter image description here

Basically, I have a method called getToken that provide token to client applications. Before providing token CORS Filter is setup and the user is validated.

If user is validated successfully, then Access-Control-Allow-Origin header is added.

User user = userDao.findByUsername(username);

if (!ObjectUtils.isEmpty(user)) {
    System.out.println("user.getDomainName()=="+user.getDomainName());
    if (origin.equalsIgnoreCase(user.getDomainName())) {
        logger.info("Access granted");
        responseToUse.addHeader("Access-Control-Allow-Origin", origin);
        responseToUse.addHeader("Access-Control-Allow-Methods", "GET");
        responseToUse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(requestToUse, responseToUse);
    }
}

Now, I tried to send a request to a URL thinking that browser will not provide response for that url but the browser is sending a valid response as shown in above picture.

Why is the browser not sending a valid response for cross-origin request? In this case the response should have been empty or invalid json


Solution

  • Now, I tried to send a request to a URL thinking that browser will not provide response for that url but the browser is sending a valid response as shown in above picture.

    The browser isn't sending anything, the server is. The Same Origin Policy doesn't prevent the server from sending a response, it controls whether or not a script can read it. If your cross origin script tries to read that response it won't be able to.

    CORS isn't a substitute for standard authentication controls. It's meant to protect the user from malicious sites, not to protect your server from the user (who, as you see, is free to read the response).