Creating web services

Using basic authentication

In general a web service takes in an HTTP request, processes it and sends a response.

Steps

  1. Take in an HTTP request using a From HTTPS channel component
  2. Parse the request into a Lua table using net.http.parseRequest{}
  3. Authenticate the user and password
    1. If authentication fails use net.http.respond{} to send a 401 (or other error) and then return (taking no further action)
    2. If authentication is successful continue to the next step
  4. Process the parsed request
  5. Optional: Take some action based on the processing
  6. Send a response using net.http.respond{}

Example

Try it now: Get the current date and time, username = admin and password = password.

This example of an authorized web service is as simple as we could make it! We just take in a request, using HTTP basic authentication, and then we return the current date and time. It’s implemented using a single channel set up with From HTTPS –> To Channel.

To run the example

  1. Create a From HTTPS –> To Channel channel
  2. Set the Source > Use Translator to “Translator”
  3. Then set the “Source>URL path” to “current_time”, and note the web link that is created
    Note: The port number will be different from that used for Iguana
  4. Load the project from this zip file Current_Date_and_Time_From_HTTPS.zip into the From HTTPS script
  5. Use the URL from step 3 to access the web service

How the example works

The raw HTTP request data comes into the main() function and we do the following:

  1. Use queue.push{data=Data} to log the incoming data.
    Note: This gives us a record of all requests. Also we can import test data from the logs into the Translator, so we can develop and test using real requests.
  2. Use net.http.parseRequest{data=Data} to parse the incoming HTTP request into a table object which gives us easy access to all the headers, cookies, post and get variables.
  3. We authenticate the user and password using the auth.BasicAuthentication() function.

Tip: If authentication fails the auth.BasicAuthentication() function sends an HTTP 401 error, and returns false (inspect the “auth” module code for details).

You can also find this module in our code repository.

Tagged: