Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers. Hi, I want to call the third party SMS APi call - TransmitSMS from my.net web application that uses framework 4.5. During the call i want to. Add(new System. I already used the credentials and body with advance rest api client tool. Request.Headers.Add('Authorization', authToken).
This chapter describes how to develop WebLogic Web service clients that conform to the Representational State Transfer (REST) architectural style using Java API for RESTful Web Services (JAX-RS).
This chapter includes the following sections:
About RESTful Web Service Client Development
The Jersey JAX-RS RI provides a client API for developing RESTful Web services clients. To access the client API, you create an instance of the
com.sun.jersey.api.client.Client
class and then use that instance to access the Web resource and send HTTP requests.Note:
A standard client API will be supported as part of the JSR-311 JAX-RS 2.0 specification.
The following sections provide more information about RESTful Web service client development:
Summary of Tasks to Develop RESTful Web Service Clients
The following table summarizes a subset of the tasks that are required to develop RESTful Web service clients. For more information about advanced tasks, see More Advanced RESTful Web Service Client Tasks.
Table 4-1 Summary of Tasks to Develop RESTful Web Service Clients
Task | More Information |
---|---|
Create an instance of the com.sun.jersey.api.client.Client class. | |
Create an instance of the Web resource. | |
Send requests to the resource. For example, HTTP requests to GET, PUT, POST, and DELETE resource information. | |
Receive responses from the resource. |
Example of a RESTful Web Service Client
The following provides a simple example of a RESTful Web service client that can be used to call the RESTful Web service defined in Example 2-1, 'Simple RESTful Web Service'. In this example:
- The
Client
instance is created to access the client API. For more information, see Creating and Configuring a Client Instance. - The
WebResource
instance is created to access the Web resource. For more information, see Creating a Web Resource Instance. - A
get
request is sent to the resource. For more information, see Sending Requests to the Resource. - The response is returned as a String value. For more information about receiving the response, see Receiving a Response from a Resource.
Additional examples are listed in Learn More About RESTful Web Services.
Example 4-1 Simple RESTful Web Service Client Example
Creating and Configuring a Client Instance
To access the Jersey JAX-RS RI client API, create an instance of the
com.sun.jersey.api.client.Client
class. For more information, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/Client.html
.Optionally, you can pass client configuration properties when creating the client instance, as defined in Table 4-2, by defining a
com.sun.jersey.api.client.Client.ClientConfig
and passing the information to the create
method. For more information, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/ClientConfig.html
.Table 4-2 RESTful Web Service Client Configuration Properties
Property | Description |
---|---|
PROPERTY_BUFFER_RESPONSE_ENTITY_ON_EXCEPTION | Boolean value that specifies whether the client should buffer the response entity, if any, and close resources when a UniformInterfaceException is thrown. This property defaults to true . |
PROPERTY_CHUNKED_ENCODING_SIZE | Integer value that specifies the chunked encoding size. A value equal to or less than 0 specifies that the default chunk size should be used. If not set, then chunking will not be used. |
PROPERTY_CONNECT_TIMEOUT | Integer value that specifies the connect timeout interval in milliseconds. If the property is 0 or not set, then the interval is set to infinity. |
PROPERTY_FOLLOW_REDIRECTS | Boolean value that specifies whether the URL will redirect automatically to the URI declared in 3xx responses. This property defaults to true . |
PROPERTY_READ_TIMEOUT | Integer value that specifies the read timeout interval in milliseconds. If the property is 0 or not set, then the interval is set to infinity. |
Example 4-2 provides an example of how to create a client instance.
Example 4-3 provides an example of how to create a client instance and pass configuration properties to the
create
method.Example 4-3 Creating and Configuring a Client Instance
Alternatively, you can configure a client instance after the client has been created, by setting properties on the map returned from the
getProperties
method or calling a specific setter method.Example 4-4 provides an example of how to configure a client after it has been created. In this example:
PROPERTY_FOLLOW_REDIRECTS
is configured by setting the property on the map returned from thegetProperties
method.PROPERTY_CONNECT_TIMEOUT
is configured using the setter method.
Example 4-4 Configuring a Client Instance After It Has Been Created
Creating a Web Resource Instance
Before you can issue requests to a RESTful Web service, you must create an instance of
com.sun.jersey.api.client.WebResource
or com.sun.jersey.api.client.AsyncWebResource
to access the resource specified by the URI. The WebResource
or AsyncWebResource
instance inherits the configuration defined for the client instance. For more information, see:WebResource
:http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/WebResource.html
AsyncWebResource
:http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/AsyncWebResource.html
Note:
Because clients instances are expensive resources, if you are creating multiple Web resources, it is recommended that you re-use a single client instance whenever possible.
Example 4-5 provides an example of how to create an instance to a Web resource hosted at
http://example.com/helloworld
.Example 4-5 provides an example of how to create an instance to a Web resource hosted at
http://example.com/helloworld
.Example 4-6 Creating an Asynchronous Web Resource Instance
Sending Requests to the Resource
Use the
WebResource
or AsyncWebResource
instance to build requests to the associated Web resource, as described in the following sections:How to Build Requests
Requests to a Web resource are structured using the builder pattern, as defined by the
com.sun.jersey.api.client.RequestBuilder
interface. The RequestBuilder
interface is implemented by com.sun.jersey.api.client.WebResource
, com.sun.jersey.api.client.AsyncWebResource
, and other resource classes.You can build a request using the methods defined in Table 4-3, followed by the HTTP request method, as described in How to Send HTTP Requests. Examples of how to build a request are provided in the sections that follow.
For more information about
RequestBuilder
and its methods, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/RequestBuilder.html
.Table 4-3 Building a Request
Method | Description |
---|---|
accept() | Defines the acceptable media types. See How to Configure the Accept Header. |
acceptLanguage() | Defines the acceptable languages using the acceptLanguage method. |
cookie() | Adds a cookie to be set. |
entity() | Configures the request entity. See How to Configure the Request Entity. |
header() | Adds an HTTP header and value. See How to Configure the Accept Header. |
type() | Configures the media type. See How to Configure the Request Entity. |
How to Send HTTP Requests
Table 4-4 list the
WebResource
and AsyncWebResource
methods that can be used to send HTTP requests.In the case of
AsyncWebResource
, a java.util.concurrent.Future<V>
object is returned, which can be used to access the result of the computation later, without blocking execution. For more information about Future<V>, see http://docs.oracle.com/javase/6/docs/api/index.html?java/util/concurrent/Future.html
.Table 4-4 WebResource Methods to Send HTTP Requests
Method | Description |
---|---|
get() | Invoke the HTTP GET method to get a representation of the resource. |
post() | Invoke the HTTP POST method to create or update the representation of the specified resource. |
put() | Invoke the HTTP PUT method to update the representation of the resource. |
delete() | Invoke the HTTP DELETE method to delete the representation of the resource. |
If the response has an entity (or representation), then the Java type of the instance required is declared in the HTTP method.
Example 4-7 provides an example of how to send an HTTP GET request. In this example, the response entity is requested to be an instance of
String.
The response entity will be de-serialized to a String
instance.Example 4-8 provides an example of how to send an HTTP PUT request and put the entity
foo:bar
into the Web resource. In this example, the response entity is requested to be an instance of com.sun.jersey.api.client.ClientResponse
.Example 4-8 Sending an HTTP PUT Request
If you wish to send an HTTP request using a generic type, to avoid type erasure at runtime, you need to create a
com.sun.jersey.api.client.GenericType
object to preserve the generic type. For more information, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/GenericType.html
.Example 4-9 provides an example of how to send an HTTP request using a generic type using
GenericType
to preserve the generic type.Example 4-9 Sending an HTTP GET Request Using a Generic Type
How to Pass Query Parameters
You can pass query parameters in the GET request by defining a
javax.ws.rs.core.MultivaluedMap
and using the queryParams
method on the Web resource to pass the map as part of the HTTP request.For more information about
MultivaluedMap
, see http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/MultivaluedMap.html
.Example 4-10 provides an example of how to pass parameters in a GET request to a Web resource hosted at
http://example.com/helloworld
, resulting in the following request URI: http://example.com/base?param1=val1¶m2=val2
How to Configure the Accept Header
Configure the
Accept
header for the request using the accept
method on the Web resource.Example 4-11 provides an example of how to specify
text/plain
as the acceptable MIME media type in a GET request to a Web resource hosted at http://example.com/helloworld
.How to Add a Custom Header
Add a custom header to the request using the
header
method on the Web resource.Example 4-12 provides an example of how to add a custom header
FOO
with the value BAR
in a GET request to a Web resource hosted at http://example.com/helloworld
.How to Configure the Request Entity
Configure the request entity and type using the
entity
method on the Web resource. Alternatively, you can configure the request entity type only using the type
method on the Web resource.Example 4-13 provides an example of how to configure a request entity and type.
Example 4-14 provides an example of how to configure the request entity media type only.
Example 4-14 Configuring the Request Entity Media Type Only
Receiving a Response from a Resource
You define the Java type of the entity (or representation) in the response when you call the HTTP method, as described in How to Send HTTP Requests.
If response metadata is required, declare the Java type
com.sun.jersey.api.client.ClientResponse
as the response type. the ClientResponse
type enables you to access status, headers, and entity information.The following sections describes the response metadata that you can access using the
ClientResponse
. For more information about ClientResponse
, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/ClientResponse.html
.How to Access the Status of Request
Access the status of a client response using the
getStatus
method on the ClientResponse
object. For a list of valid status codes, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/ClientResponse.Status.html
.Example 4-11 provides an example of how to access the status code of the response.
How to Get the Response Entity
Get the response entity using the
getEntity
method on the ClientResponse
object.Example 4-11 provides an example of how to get the response entity.
More Advanced RESTful Web Service Client Tasks
For more information about advanced RESTful Web service client tasks, including those listed below, see the Jersey 1.9 User Guide at
http://jersey.java.net/nonav/documentation/1.9/user-guide.html
.- Adding new representation types
- Using filters
- Enabling security with HTTP(s) URLConnection
What is WS Security?
WS Security is a standard that addresses security when data is exchanged as part of a Web service.This is a key feature in SOAP that makes it very popular for creating web services.
Security is an important feature in any web application. Since almost all web applications are exposed to the internet, there is always a chance of a security threat to web applications. Hence, when developing web-based applications, it is always recommended to ensure that application is designed and developed with security in mind.
In this tutorial, you will learn-
Security Threats and Countermeasure
To understand security threats which can be hostile to a web application, let's look at a simple scenario of a web application and see how it works in terms of Security.
One of the security measures available for the HTTP is the HTTPS protocol. HTTPS is the secure way of communication between the client and the server over the web. HTTPS makes use of the Secure Sockets layer or SSL for secure communication. Both the client and the server will have a digital certificate to identify themselves as genuine when any communication happens between the client and the server.
In a standard HTTPS communication between the client and the server, the following steps take place
- The client sends a request to the server via the client certificate. When the server sees the client certificate, it makes a note in its cache system so that it knows the response should only go back to this client.
- The server then authenticates itself to the client by sending its certificate. This ensures that the client is communicating with the right server.
- All communication thereafter between the client and server is encrypted. This ensures that if any other users try to break the security and get the required data, they would not be able to read it because it would be encrypted.
But the above type of security will not work in all situations. There can come a time when the client can talk to multiple servers. An example given below shows a client talking to both a database and a web server at a time. In such cases, not all information can pass through the https protocol.
This is where SOAP comes in action to overcome such obstacles by having the WS Security specification in place. With this specification, all security related data is defined in the SOAP header element.
The header element can contain the below-mentioned information
- If the message within the SOAP body has been signed with any security key, that key can be defined in the header element.
- If any element within the SOAP Body is encrypted, the header would contain the necessary encryptions keys so that the message can be decrypted when it reaches the destination.
In a multiple server environments, the above technique of SOAP authentication helps in the following way.
- Since the SOAP body is encrypted, it will only be able to be decrypted by the web server that hosts the web service. This is because of how the SOAP protocol is designed.
- Suppose if the message is passed to the database server in an HTTP request, it cannot be decrypted because the database does not have right mechanisms to do so.
- Only when the request actually reaches the Web server as a SOAP protocol, it will be able to decipher the message and send the appropriate response back to the client.
We will see in the subsequent topics on how the WS Security standard can be used for SOAP.
Web Service Security Standards
As discussed in the earlier section, the WS-Security standard revolves around having the security definition included in the SOAP Header.
The credentials in the SOAP header is managed in 2 ways.
First, it defines a special element called UsernameToken. This is used to pass the username and password to the web service.
The other way is to use a Binary Token via the BinarySecurityToken. This is used in situations in which encryption techniques such as Kerberos or X.509 is used.
The below diagram shows the flow of how the security model works in WS Security
Below are the steps which take place in the above workflow
- A request can be sent from the Web service client to Security Token Service. This service can be an intermediate web service which is specifically built to supply usernames/passwords or certificates to the actual SOAP web service.
- The security token is then passed to the Web service client.
- The Web service client then called the web service, but, this time, ensuring that the security token is embedded in the SOAP message.
- The Web service then understands the SOAP message with the authentication token and can then contact the Security Token service to see if the security token is authentic or not.
The below snippet shows the format of the authentication part which is part of the WSDL document. Now based on the below snippet, the SOAP message will contain 2 additional elements, one being the Username and the other being the Password.
When the SOAP Message is actually passed between the clients and the server, the part of the message which contains the user credentials could look like the one shown above. The wsse element name is a special element named defined for SOAP and means that it contains security based information.
How to build secure web services
Now let's look at SOAP web service security example. We will build a web service security upon the example demonstrated earlier in the SOAP chapter and will add a security layer to it.
In our example, we are going to create a simple web service, which will be used to return a string to the application which calls the web service. But this time, around, when the web service is invoked, the credentials need to be supplied to the calling service. Let's follow the below steps to create our SOAP web service and add the security definition to it.
Step 1) The first step is to create an empty Asp.Net Web application. From Visual Studio 2013, click on the menu option File->New project.
Once you click on the New Project option, Visual Studio will then give you another dialog box for choosing the type of project and to give the necessary details of the project. This is explained in the next step
Step 2) In this step,
- Ensure that you first choose the C# web template for ASP.NET Web application. The project has to be of this type in order to create web services project. By choosing this option, Visual Studio will then carry out the necessary steps to add required files which are required by any web-based application.
- Give a name for your project which in our case has been given as 'webservice.asmx.' Then make sure to give a location, where the project files will be stored.
Once done you will see the project file created in your solution explorer in Visual Studio 2013.
Step 3) In this step,
We are going to add a Web service file to our project
- First Right-click on the project file as shown below
- Once you right-click on the project file, you have the chance to choose the option 'Add->Web Service (ASMX) to add a web service file. Just provide a name of Tutorial Service for the web service name file.
The above step will prompt a dialog box,wherein one can enter the name of the web service file. So in the below dialog box, enter the name of TutorialService as the file name.
Step 4) Add the following code to your Tutorial Service asmx file. The below snippet of code is used to add a custom class which will be used to change the SOAP Header when the SOAP message is generated. Since we now want to add security credentials to the SOAP header, this step is required.
Code Explanation:-
- We are now creating a separate class called AuthHeader which is of type SoapHeader class. Whenever you want to change what gets passed in the SOAP header, one needs to create a class which uses the in-built SoapHeader class of .Net. By customizing the SOAPheader, we now have the ability to pass a 'Username' and 'Password' when the web service is called.
- We then define variables of 'UserName' and 'Password' which are of type string. They will be used to hold the values of the username and password which are passed to the web service.
Step 5) As the next step, the following code needs to be added to the same TutorialService.asmx file. This code actually defines the function of our web service. This function returns a string 'This is a Guru99 Web service' to the client. But this time, the string will only be returned if the client application passes the credentials to the web service.
Code Explanation:-
- Here, we are creating an object of the AuthHeader class which was created in the earlier step. This object will be passed to our Guru99Webservice in which the username and password can be closely examined.
- The [SoapHeader] attribute is used now to specify that when the Web service is called, it needs to have the user name and password passed.
- In this block of code, we are actually examining the user name and password passed when the web service is called. If the Username is equal to 'Guru99' and the password is equal to 'Guru99Password' then the message of 'This is a Guru99 Web service' is passed to the client. Else an error will be sent to the client if the wrong user id and password are passed.
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
The above output is shown when the program is run, which means that the Web service is now available. Let's click on the Service Description link.
From the service description, you will now be able to see that the username and password are elements of the WSDL file. These parameters need to be sent when the web service is invoked.
Web Service Security Best Practices
Following are the security considerations which should be noted when working with Web services
- Auditing and Log management – Use application logging to log all requests, which comes to the web services. This gives a detailed report on who has invoked the web service and can help in Impact analysis if any security breach occurs.
- Flow of calls to the web service – Try to note the flow of the calls in web services. By default, an application could call multiple web services request with Authentication tokens passed between these web services. All calls between web services need to be monitored and logged.
- Sensitive Information - Do not include sensitive information in your log entries such as passwords or credit card numbers or any sort of other confidential information. If there is an event which has any of this information, it needs to be discarded before logging.
- Track Business Operations - Track significant business operations. For example, instrument your application to record access to particularly sensitive methods and business logic. Let's take an example of an online shopping application. There are multiple steps in a typical application such as the choosing the items to be purchased, the items loaded in the cart and then the final purchase. This entire business workflow needs to be tracked by the web service.
- Proper Authentication - Authentication is the mechanism by which the clients can establish their identity with the web service using a certain set of credentials that can prove that identity. One should never store the user credentials, and hence, if WS Security is used to call the web service, it has to be noted that the web service should not store the credentials which are sent in the SOAP header. These should be discarded by the web service.
Summary
- SOAP provides an additional layer called WS Security for providing additional security when calls are made to Web services.
- The WS Security can be called with a simple username or password or can be used with Binary certificates for authentication
- We have seen that in .Net we can customize the Web service to have a user name and password passed as part of the SOAP header element.