Using basic authentication for web service security

Basic authentication is one of the simplest and thus the least secure authentication mechanism. It sends a combined string, which contains username and password encoded with base64 encoding, inside a special HTTP header. Password and username can be very easily discovered, if the HTTP request is intercepted by an attacker. On the other hand, if a request goes through using the HTTPS protocol, then header discovery is less likely to happen. The combination of HTTPS and basic authentication makes a rather popular choice as a starting security scheme for web services.

In this recipe, we will demonstrate how to use the HTTPBuilder library, which we already covered in previous recipes (for example, the Issuing a SOAP request and parsing a response recipe), to achieve the basic request authentication.

How to do it...

The following steps present how simple it is to inject basic authentication credentials into your requests:

  1. First of all we need to create an instance of HTTPBuilder pointing to our service URL:
    def service = new HTTPBuilder('https://localhost:5000/')
  2. Username (groovy) and password (cookbook) values can be set in the following way:
    service.auth.basic('groovy', 'cookbook')
  3. At this point, you can construct HTTP requests to the secured web service as follows:
    def response = service.get(path: 'secret-service')

How it works...

Under the hood, the HTTPBuilder library just encodes username and password into the required HTTP header. All other HTTPBuilder's methods can be used in the same way they were used in other recipes.

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

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