Saturday 10 March 2018

Cross-origin resource sharing (CORS) example using servlets

CORS stands for Cross Origin Resource Sharing. By using CORS, web application from one domain can access the resources from the application that is deployed in another domain.

Below step-by-step procedure explains how CORS works in real time?
we should handle CORS. When the application 'APP1' (Assume APP1 is deployed on domain D1) from browser 'B1' wants to access the resource 'R2' of the application 'APP2' (Assume 'APP2' is deployed on domain D2). 

Below step-by-step procedure explains, how can we build a CORS application using servlets.

Step 1: Browser 'B1' send the OPTIONS request to the application 'APP2' with an ‘Origin’ HTTP header. The ‘Origin’ header contains the domain of the application ‘APP1’.

When a page from http://www.sample.com attempts to access a user's data in http://www.usersTree.com, the following request header would be sent to http://www.usersTree.com:



Step 2: Application 'APP2' receives the request and either approve/reject the request.

Step 3: Upon successful approval from APP2, browser 'B1' fires the actual request and access the resource.

You should be known about below HTTP headers while working with CORS.

Request headers
a. Origin: Origin header specifies the host, where the fetch originates from.

Syntax
Origin: ""
Origin: <scheme> "://" <hostname> [ ":" <port> ]

Example

b. Access-Control-Request-Method
It tells about the HTTP method going to be used when the actual request is made.

Syntax
Access-Control-Request-Method: <method>

Example
Access-Control-Request-Method: POST

c. Access-Control-Request-Headers
It tells which HTTP headers will be used when the actual request is made.

Syntax
Access-Control-Request-Headers: <header-name>, <header-name>, ...

Example
Access-Control-Request-Headers: Content-Type, Authorization

Response headers
a. Access-Control-Allow-Origin
It specify the origin that are allowed to access your resource.

Syntax
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>

Example
Access-Control-Allow-Origin: https://self-learning-java-tutorial.blogspot.com

How can I allow my resource to be accessed by all origins?
By setting the value of the header 'Access-Control-Allow-Origin' to *, you can allow the resource to be shared by all origins.
Access-Control-Allow-Origin: *

b. Access-Control-Allow-Credentials
By default, CORS does not include cookies on cross-origin requests. When server responds by setting the header 'Access-Control-Allow-Credentials' to true, means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
Syntax
Access-Control-Allow-Credentials: <true/false>

Example
Access-Control-Allow-Credentials: true

c. Access-Control-Expose-Headers
It specifies the headers that can be exposed as part of the response by listing their names.

Below headers are exposed by default.
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma

Syntax
Access-Control-Expose-Headers: <header-name>, <header-name>, ...

Example
Access-Control-Expose-Headers: Content-Length, Host, Keep-Alive

d. Access-Control-Max-Age
This header specifies, how long the results of the request are cached.

Syntax
Access-Control-Max-Age: <seconds>

Example
Access-Control-Max-Age: 300

e. Access-Control-Allow-Methods
It specifies the methods that are allowed while accessing the resource.

Syntax
Access-Control-Allow-Methods: <method>, <method>, ...

Example
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS


f. Access-Control-Allow-Headers
It specifies the headers that can be used in actual request.

Syntax
Access-Control-Allow-Headers: <header-name>, <header-name>, ...

Example
Access-Control-Allow-Headers: Age, Content-Type
  
Now, let’s build a simple application.

As you see above diagram, I am going to build two applications
a.   APP1
b.   APP2

APP1 requests welcome message service of APP2. APP2 sends the response, if the request comes from the domain localhost:8080.

Develop Application APP1
Create a new dynamic web project in Eclipse.

Create new file ‘index.jso’ with below content.


index.jsp

<!DOCTYPE html>
<html>
<head>
<script
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
 $(document).ready(function() {
  $("button").click(function() {
   $("#corsResponse").load("http://localhost:9090/APP2/welcomeMessage");
  });
 });
</script>
</head>
<body>
 <h2>CORS Demo Application</h2>
 <div id="corsResponse"></div>
 <br />
 <button>Get Welcome Message</button>
</body>
</html>

Develop application APP2
Create new dynamic web project APP2 in Eclipse.

Create new package 'com.app2.sample' and define the servelt 'WelcomeMessage' like below.


WelcomeMessage.java

package com.app2.sample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/welcomeMessage")
public class WelcomeMessage extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public WelcomeMessage() {
  super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  handleCORSHeadersOptions(request, response);
  PrintWriter writer = response.getWriter();
  writer.write("Hello, Very Good Morning");
 }

 protected void doOptions(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  handleCORSHeadersOptions(request, response);
 }

 private void handleCORSHeadersOptions(HttpServletRequest request, HttpServletResponse response) {
  String originHeader = request.getHeader("Origin");

  System.out.println("Origin header is coming as : " + originHeader);

  response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
  response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
  response.setHeader("Access-Control-Max-Age", "600");
  response.setHeader("Access-Control-Allow-Credentials", "true");
  response.setStatus(HttpServletResponse.SC_OK);

 }

}

I configured ‘APP1’ to run on port 8080 and ‘APP2’ to run on port 9090.

Run the application ‘APP2’.


Run the application ‘APP1’. You can able to see below kind of image.

Click on the button ‘Get Welcome Message’. You can able to see the welcome message in web page. As you see below image, response headers specific to CORS request are come as part of the response.


Now let’s comment the code in the method 'handleCORSHeadersOptions' of servlet 'WelcomeMessage.java' and rerun the application.
Since the CORS headers are not coming from the server, application will not render the response in web page.

Reference







Previous                                                 Next                                                 Home

No comments:

Post a Comment