Wednesday, March 28, 2012

Secured Webservice: Authenticated REST Webservice

Use Case:  Communication between web services can be secured.

Method:

JAVA and .NET method to call/make Authenticated REST web-service.

Ø                   In case of Java applications, we need to send REFERER as below :
o        httpUrlConnection.setRequestProperty(“REFERER”, “NEWRAM”);
Ø                   In case of .NET applications, we need to send REFERER as below :
o        webClient.Headers.Set(“REFERER”, “NEWRAM”);

Calling Authenticated REST webservice using a simple JAVA program:


import java.io.BufferedInputStream;
import java.net.URL;
import java.net.HttpURLConnection;

====

URL url = new URL(webserviceURL);                                 

HttpURLConnection connection = (HttpURLConnection)url.openConnection();                           
connection.setDoOutput(true);
connection.setRequestProperty( “REFERER”, “NEWRAM”);
connection.setRequestMethod("POST");

int bufLength = 2048;    //Buffer length is mentioned explicitly to get max space
BufferedInputStream bufferInputStream = new  
BufferedInputStream(connection.getInputStream(), bufLength);
            
byte[] outputByteArray = new byte[bufLength];
int size;
while( (size = bufferInputStream.read(outputByteArray, 0,bufLength)) != -1)
{

String outputString = new String(outputByteArray, 0, size, "UTF-8");
        stringBuffer.append(outputString);
}

if( request.getHeader("REFERER")==null )                                       //  if Authentication fails
{

stringBuffer.setLength(0);
stringBuffer.append("Service can't be accessed directly.");       // Send Error Message instead of Output
}