Configuration of allowed origins

The origin is the scope of the privilege by the agent. A variety of content exists in various formats created by numerous authors, something out of which may be harmful. The content created by one origin can freely interact with the content created by another origin. The agents have the facility to set up the rules under which one content may interact with the others; these are called same-origin policy.

Let's take an example of HTML where we have form submission. Whenever the user agent enters the data, the entered data is exported to the URL. Here, the URL declares its trust on the integrity of the information that the script file has received through the URI.

The different URIs are http://packt.com/, http://packt.com:8080/, http://www.packt.com/, https://packt.com:80/, https://packt.com/, and http://packt.org/.

There are three ways to configure origin, and they are as follows:

  • Allowing same origin
  • Allowing a specified list of origins
  • Allowing all origins

Let's first discuss in detail the creation and use of WebSocket for the client-server communication as follows:

  1. Creation of WebSocket: The following code is used to create WebSocket:
WebSocket socket=  new WebSocket( URL, protocols); 

In the preceding statement, the URL contains the following:

    • Schema: The URL must contain either ws, denoting insecure connection, or wss, denoting secure connections
    • Host: This is a name or IP of the server
    • Port: This is the remote port number through which you want to get connected to the server; ws connection, by default, uses port number 80 and wss uses 443
    • Resource name: This is the path URL of the resource which we want to fetch

We can write the URL for WebSocket as follows:

scheme://host_name:port_no/resource_path 
ws://host_name:port_no/resource_path 
wss://host_name:port_no/resource_path 
  1. Closing WebSocket: To close the connection, we will use the close() method as close(code, reason).
Code is a numeric status sent to the server. 1000 indicates normal closing of connections.
  1. States of WebSocket: The following are the connection states of WebSocket, giving information regarding its state:
    • Connecting: This means that WebSocket is constructed, and it is attempting to connect to the specified URL. This state is considered as the connecting state, having a ready state as 0.
    • Open: Once WebSocket is successfully connected to the URL, it will enter the open state. The data can be sent to and from the network only when WebSocket is in the open state. The ready state value of open state is 1.
    • Closing: WebSocket does not close directly; it must communicate to the server to inform that it is disconnecting. This state is considered as the closing state. The ready state value of open state is 2.
    • Closed: After the successful disconnection from the server, WebSocket enters the closed state. WebSocket in the closed state has a ready state value of 3.
  1. Event Handling in WebSocket: WebSocket works on the principle of event handling, where the callback methods get invoked to complete the process. The following are the events that occur in the life cycle of WebSocket:
    • onopen: This event handler gets called when WebSocket transits to the open state.
    • onmessage: This event handler gets called when WebSocket receives data from the server. The received data gets stored in the data field of the message event.

The data field has the following parameters:

    • onclose: This event handler gets called when WebSocket is closed. The event object gets passed to onclose. It has three fields, which are as follows:
    • code: This is a numeric status value provided by the server.
    • reason: This is a string describing the close event.
    • wasClean: This has a Boolean value indicating whether the connection closed without any problem. Under normal circumstances, wasClean is true.
    • onerror: When WebSocket encounters any problem, the onerror event handler gets called. The event passed to the handler will be a standard error object, which includes the name and message fields.
  1. Sending the data: Data transmission happens via the send() method, which deals with UTF-8 text data, data of type ArrayBuffer, and data of type blob. The bufferedAmount property with its value as zero ensures that the data is sent successfully.

Let's develop a demo for WebSocket with the help of the following steps to find the capital of a country:

  1. Create Ch10_Spring_Message_Handler as a dynamic web application.
  2. Add jars for the Spring core, Spring web, spring-websocket, and spring-messaging modules. Also, add jars for Jackson.
  3. Now, let's add MyMessageHandler as a child of TextWebSocketHandler in the com.packt.ch10.config package. Override the methods for handling message, WebSocket connection, and connection closing, as follows:
public class MyMessageHandler extends TextWebSocketHandler { 
  List<WebSocketSession> sessions = new
CopyOnWriteArrayList<>(); @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { String country = message.getPayload(); String reply="No data available"; if(country.equals("India")) { reply="DELHI"; } else if(country.equals("USA")) { reply="Washington,D.C"; } System.out.println("handling message"); for(WebSocketSession webSsession:sessions){ session.sendMessage(new TextMessage(reply)); } } @Override public void afterConnectionEstablished(WebSocketSession session) throws IOException { // Handle new connection here System.out.println("connection established:hello"); sessions.add(session); session.sendMessage(new TextMessage("connection establieshed:hello")); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws IOException { // Handle closing connection here System.out.println("connection closed : BYE"); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws IOException { session.sendMessage(new TextMessage("Error!!!!!!")); } }
  1. This MessageHandler needs to register with WebSocketConfigurer for the /myHandler URL for all origins, as shown in the following piece of code:
@Configuration 
@EnableWebSocket 
public class MyWebSocketConfigurer extends 
  WebMvcConfigurerAdapter implements WebSocketConfigurer { 
  @Override 
  public void 
registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("*"); } @Bean public WebSocketHandler myHandler() { return new MyMessageHandler(); } // Allow the HTML files through the default Servlet @Override public void configureDefaultServletHandling (DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
  1. Add Front Controller mapping in web.xml as we did in earlier applications, with its servlet name as books.
  2. Add books-servlet.xml to add a bean for viewResolver. You can decide adding it as a bean depending upon the application requirement.
  3. Also, add configuration to enable Spring web MVC as follows:
<mvc:annotation-driven /> 
  1. Add country.jsp as a JSP page having a list of countries where the user can select a country from a drop-down menu to get the name of its capital:
<div> 
  <select id="country"> 
        <option value="India">INDIA</option> 
        <option value="USA">U.S.A</option> 
  </select><br> 
  <br> <br> 
   <button id="show" onclick="connect();">Connect</button> 
      <br /> <br /> 
    </div> 
  <div id="messageDiv"> 
      <p>CAPITAL WILL BE DISPLAYED HERE</p> 
      <p id="msgResponse"></p> 
  </div> 
</div> 

We even can write the XML based configuration using websocket namespace as discussed earlier.

  1. Add SockJS support by adding sockjs-0.3.4.js in your resources, or by adding the following line of code:
<script type="text/javascript" 
  src="http://cdn.sockjs.org/sockjs-0.3.4.js"></script>
  1. On form submission, a method of JavaScript gets invoked, where we handle the WebSocket events, such as onopen, onmessage, and the likes, as discussed earlier:
<script type="text/javascript"> 
  var stompClient = null; 
  function setConnected(connected) { 
    document.getElementById('show').disabled = connected; 
  } 
  function connect() { 
    if (window.WebSocket) { 
      message = "supported"; 
      console.log("BROWSER SUPPORTED"); 
    } else { 
      console.log("BROWSER NOT SUPPORTED"); 
    } 
    var country = document.getElementById('country').value; 
    var socket = new WebSocket( 
      "ws://localhost:8081/Ch10_Spring_Message_Handler 
        /webS/myHandler"); 
    socket.onmessage=function(data){ 
      showResult("Message Arrived"+data.data) 
    }; 
    setConnected(true); 
    socket.onopen = function(e) { 
      console.log("Connection established!"); 
      socket.send(country); 
      console.log("sending data"); 
    }; 
  } 
  function disconnect() { 
    if (socket != null) { 
      socket.close(); 
    } 
    setConnected(false); 
    console.log("Disconnected"); 
  } 
  function showResult(message) { 
    var response = document.getElementById('messageDiv'); 
    var p = document.createElement('p'); 
    p.style.wordWrap = 'break-word'; 
    p.appendChild(document.createTextNode(message)); 
    response.appendChild(p); 
  } 
</script>

We already discussed how to write the WebSocket URLs and event-handling mechanism.

  1. Deploy the application and access the page. Select the country from the drop-down menu and click on the SHOW CAPITAL button. A message displaying the name of the capital will appear.

The following diagram shows the flow of the application:

  1. We added console logs as well as alert messages to know the progress and the to-and-fro movement of the messages. You can customize it as per requirement, or you can completely omit it as well.

In the earlier example, we used WebSocket for communication, but its support is limited. SockJS is a JavaScript library that provides objects such as WebSocket.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.100.180