Showing posts with label Web services. Show all posts
Showing posts with label Web services. Show all posts

Friday, March 27, 2015

Web services - Part6


Webservices Security

Web Services use known protocols, ports, descriptors and methods to access and “expose” back-end components to the client side. This means that any Web service vulnerable to following and more:
  • SQL injections
  • Scripting exploits
  • Denial of Service attacks: an attacker does a small amount of work on a message that causes the target system to devote all its resources to a specific task so that it cannot provide any services to valid requests.
  • Message monitoring and copying
  • Message source spoofing: An attacker alters an original message by inserting, removing or modifying content created by the originator, and the faked message is then mistaken by the receiver as being the originator’s real intention. In addition, an attacker may also construct a new fake message to fool the receiver into believing it to have come from a valid sender.
  • Message (payload) manipulation ( changing send data – in transit)
  • Transmission of viruses (in message or as an attachment)
  • Transactional Attacks
  • Replay of message parts: an attacker replays parts of the captured message to the receiver with the aim of gaining access to an unauthorised system, or causing the receiver to take unnecessary action.

Web services security aspects includes Authentication, Authorization, Confidentiality/privacy, Integrity/non repudiation
·         Authentication – It’s verification of user identity which is verified based on the credentials provided by user
·         Authorization or Access Control - it is granting access to specific resources after authentication of user
·         Confidentiality/privacy - Keeping information secret. For example encrypting the content of send messages.
·         Integrity/non repudiation – it’s surety that a message remains unaltered during transit. Digital signature is used to validate the signature and provides non-repudiation.

There are two types of security requirements for web services, transport level (Secure Socket Layer) and application/message level.

Transport-level Security
SSL (Secure Socket Layer) or TLS (Transport Layer Security) is the most widely used transport-level data-communication protocol. It provide Authentication, Confidentiality (encrypted data exchanged), Message integrity (uncorrupted data) and Secure key exchange between client and server.

SSL provides a secure communication channel when data is on transit, however, when the data is not "in transit," the data is not protected. This means in multi-step transactions the environment vulnerable to attacks. (SSL provides point-to-point security, as opposed to end-to-end security.)

Message-level Security

Message level security is an application layer service and facilitates the protection of message data between applications. Message-level security is based on XML frameworks defining confidentiality, integrity, authenticity; message structure; trust management and federation. Message structure and message security are implemented by SOAP and its security extension, WS-Security. WS-Security defines how to attach XML Signature and XML Encryption headers to SOAP messages. In addition, WS-Security provides profiles for 5 security tokens: Username (with password digest), X.509 certificate, Kerberos ticket, Security Assertion Markup Language (SAML) assertion, and REL (rights markup) document.

Message level security is used in scenarios where application is designed to use mostly asynchronous queues. SOAP based services use Message Level Security. In message level security, security information is contained within the SOAP message, which allows security information to travel along with the message. For example, a portion of the message may be signed by a sender and encrypted for a particular receiver. In this case message can pass through multiple nodes before delivered to destination and encrypted part of message is opaque to these intermediate nodes. For this reason, message-level security is also referred as end-to-end security.



Monday, March 23, 2015

Web services - Part5

How to create and consume RESTful webservices

In this blog I will explain how to create and consume RESTful web service with JAX-RS using Jersey.

Java API for RESTful Web Services (JAX-RS) is a Java programming language API that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. (http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services )

In order to simplify development of RESTful Web services and their clients in Java, a standard and portable JAX-RS API has been designed. Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation (https://jersey.java.net/).

I have used Eclipse Indigo, JDK 1.7, Jersey1.19 (you can download ‘Jersey 1.19 ZIP bundle’ zip from https://jersey.java.net/download.html ), Apache Tomcat 5.5
Let’s see step by step to create Restful webservice

SETP1: Create new Dynamic Web Project



STEP2: Add downloaded jersey JARs to project lib folder. Also, you need to add dependent jars persistence-api-1.0.jar and jersey-container-servlet-core-2.17.jar.



STEP3: Create a RESTful Web Service Resource ( Java class )

package com.kmingle.webservices.restful;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Path;

@Path("/restfulExample")
public class RestfulServiceProvider {

       @GET
       @Produces(MediaType.TEXT_PLAIN)
       public String sayHello(){
              return "RESTful Hello World!";
       }
}

Here, @Path("/restfulExample") annotation before class definition tells that restfulExample  REST service can be reached in the URL .../ restfulExample. @GET annotation before method definition means that in URL .../ restfulExample, all GET requests are going to be handled by sayHello() method. You can also pass parameters in a GET request in REST services using  URI path parameter  with annotation @Path("/{parameter}") before method definition.
The @Produces annotation used in the sayHello() method specify the MIME media types or representations a resource can produce and send back to the client. If no methods in a resource are able to produce the MIME type in a client request, the Jersey runtime sends back an HTTP “406 Not Acceptable” error.


STEP4:  Do Servlet mapping in web.xml as mentioned below -

xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
       <display-name>RestfulWebServiceExample</display-name>
       <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>index.jsp</welcome-file>
              <welcome-file>default.html</welcome-file>
              <welcome-file>default.htm</welcome-file>
              <welcome-file>default.jsp</welcome-file>
       </welcome-file-list>
      
   <servlet>
    <servlet-name>RESTful_Web_Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.kmingle.webservices.restful</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>RESTful_Web_Service</servlet-name>
    <url-pattern>/restful/*</url-pattern>
  </servlet-mapping>
      
</web-app>

STEP5: Your web service is ready to run start the server and run web service in browser
URL should be (http://localhost:8080/) + ( url-pattern in web.xml) + (@Path annotation value in resource class)



RESTful webservice client( Consumer ) :
To consume this RESTful webservice we need to create a client. Let’s have a look how to create a Java Jersey client.

STEP1:  Create new Java Project



STEP2: Add jersey jars to lib folder, for that add “Web App Libraries” with RestfulWebserviceExample Project



STEP3: Create client class

package com.kmingle.webservices.restful;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class RestfulWebserviceClient {
      
       public static void main(String args[]){
              try {
                      
                     Client client = Client.create();
                     WebResource webResource = client.resource("http://localhost:8080/RestfulWebServiceExample/restful/restfulExample");
                     ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
                     if (response.getStatus() != 200) {
                            throw new RuntimeException("HTTP error code :" + response.getStatus());
                     }

                     String output = response.getEntity(String.class);
                     System.out.println("Webservice Response");
                     System.out.println(output);

              } catch (Exception e) {
                     e.printStackTrace();
              }     
             
       }

}

Output:
Webservice Response
RESTful Hello World!


My next blog will be on webservice security……

Creating SOAP Web Service                                               Webservices Security >

Friday, March 13, 2015

Web services - Part4


Creating SOAP Web Service
We will create a simple web service using eclipse, Apache Tomcat Server 5.5, Apache Axis web service runtime using “Bottom up Java Bean Web Service”
1.        Create New Dynamic Project



2.       Create new class that will be used to create Web service in Bottom up Approach ( that is using this class eclipse will generate WSDL etc )
package com.kmingle.webservices.soap;

public class HelloWebserviceClass {

       public String sayHello(String name){
              return "Hello, from "+name;
       }
}

3.        Right Click on Dynamic Web Project and select new > Web Service
Here simultaneously you can create test client also, to test the Web service.



4.        Start the server


5.        Use following link in browser to test newly created Web service



It will show following SOAP request and response in TCP/IP Monitor view ( if you have selected “Monitor the web service” in step 3 )


SOAP Request:
  
      satyendra
  

SOAP Response:
  
      hello, from satyendra
  

Further, you can explore the generate WSDL file under /WebContent/wsdl path. Below is the generate WSDL (HelloWebServiceClass.wsdl )

xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://soap.webservices.kmingle.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://soap.webservices.kmingle.com" xmlns:intf="http://soap.webservices.kmingle.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <wsdl:types>
  <schema elementFormDefault="qualified" targetNamespace="http://soap.webservices.kmingle.com" xmlns="http://www.w3.org/2001/XMLSchema">
   <element name="sayHello">
    <complexType>
     <sequence>
      <element name="name" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
   <element name="sayHelloResponse">
    <complexType>
     <sequence>
      <element name="sayHelloReturn" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
  </schema>
 </wsdl:types>

   <wsdl:message name="sayHelloResponse">

      <wsdl:part element="impl:sayHelloResponse" name="parameters">

      </wsdl:part>

   </wsdl:message>

   <wsdl:message name="sayHelloRequest">

      <wsdl:part element="impl:sayHello" name="parameters">

      </wsdl:part>

   </wsdl:message>

   <wsdl:portType name="HelloWebserviceClass">

      <wsdl:operation name="sayHello">

         <wsdl:input message="impl:sayHelloRequest" name="sayHelloRequest">

       </wsdl:input>

         <wsdl:output message="impl:sayHelloResponse" name="sayHelloResponse">

       </wsdl:output>

      </wsdl:operation>

   </wsdl:portType>

   <wsdl:binding name="HelloWebserviceClassSoapBinding" type="impl:HelloWebserviceClass">

      <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

      <wsdl:operation name="sayHello">

         <wsdlsoap:operation soapAction=""/>

         <wsdl:input name="sayHelloRequest">

            <wsdlsoap:body use="literal"/>

         </wsdl:input>

         <wsdl:output name="sayHelloResponse">

            <wsdlsoap:body use="literal"/>

         </wsdl:output>

      </wsdl:operation>

   </wsdl:binding>

   <wsdl:service name="HelloWebserviceClassService">

      <wsdl:port binding="impl:HelloWebserviceClassSoapBinding" name="HelloWebserviceClass">

         <wsdlsoap:address location="http://localhost:8080/ExampleWebProject/services/HelloWebserviceClass"/>

      </wsdl:port>

   </wsdl:service>

</wsdl:definitions>


So we have seen that creating a soap web service using tools like eclipse is much simpler than understanding its technology stacks :-) .


In my next blog we will see Implementing RESTful web service

Thursday, March 12, 2015

Web services - Part3

Types of Web services

Web services can be classified as “Big” web services and “RESTful” web services. Big web services are based on SOAP standard.RESTful web services are based on how web behaves.
The “Big” Web services technology stack (SOAP, WSDL, WSSecurity,etc.)delivers interoperability for both the Remote Procedure Call (RPC) and messaging integration styles.RESTful Web services is an alternative solution to implement remote procedure calls across the Web

'BIG' Web services key points:

-Big web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard, an XML language defining a message architecture and message formats.

- A SOAP-based design must include the following elements :

  • WSDL can be used to describe the details of the contract, which may include messages, operations, bindings, and the location of the web service. You may also process SOAP messages in a JAX-WS service without publishing a WSDL.
  • It Should also address complex nonfunctional requirements like transactions, security, addressing, coordination etc.
  • The architecture needs to handle asynchronous processing and invocation.


- SOAP integrates between client and server using WSDL.Web Services Description Language (WSDL) is an XML language for defining interfaces syntactically.XML Schema is used to describe the structure of the SOAP message.

- SOAP is an XML language defining a message architecture and message formats, hence providing a rudimentary processing protocol. The SOAP document defines a toplevel XML element called envelope, which contains a header and a body. The SOAP header  can be used for routing purposes (e.g., addressing) and Quality of Service (QoS) configuration (e.g., transactions, security, reliability).

- Using SOAP, the same message in the same format can be transported across a variety of middleware systems, which may rely on HTTP

- SOAP security is well standardized through WS-SECURITY.


REpresentational State Transfer (REST)  key points:

- The motivation behind the development of REST was to create a design pattern for how the Web should work, so that it could act as a guiding framework for the Web standards and designing Web services. REST itself is not a standard but it prescribes the use of standards such as HTTP, URL, and XML/HTML/JPEG

- The term “REST” was given by Roy Fielding.
“Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use.”  – Roy Fielding

- In the web, everything is identified by resources. When we type a URL in the browser we are actually requesting a resource present on the server. A representation of the resource (normally a page) is returned to the user which depicts the state of the application. On clicking any other link, the application transfers state with the new representation of the resource. Hence the name Representational State Transfer.

- REST-style architectures consist of clients and servers. Clients initiate requests to servers who process these requests and return responses based on these requests.These requests and responses are built around the transfer of representations of these resources.Fundamentally in REST each resource is first identified using a URL and a new resource for every service required is created.

- When using REST over HTTP, it will utilize the features available in HTTP such as caching, security in terms of TLS and authentication

- Two simples security is provided on the HTTP protocol layer such as basic authentication and communication encryption through TLS

REST architectural style describes six constraints applied to architecture:

1. Uniform Interface - Individual resources are identified using URLS.The client can manipulate the resource through the representations provided they have the permissions.A representation of a resource is a document that captures the intended state of a resource.

2. Stateless Interactions - none of the clients context is to be stored on the server side between the request. All of the information necessary to service the request is contained in the URL, query parameters, body or headers.

3. Cacheable - Clients can cache the responses.

4. Client-Server - The clients and the server are separated from each other thus the client is not concerned with the data storage thus the portability of the client code is improved while on the server side the server is not concerned with the client interference thus the server is simpler and easy to scale.

5. Layered System - At any time client cannot tell if it is connected to the end server or to an intermediate. The  intermediate layer helps to enforce the security policies and improve the system scalability by enabling load-balancing

6. Code on Demand - an optional constraint where the server temporarily extends the functionality of a client by the transfer of executable code.


In next blog we will see an example of SOAP implementation.


Total Pageviews