oauth2

20 August 2019 Link



Purpose

To provide API to connect and use services secured by the oAuth 2.0 protocol using Lua.

Dependencies


Basic Usage

The demo.lua file gets access to google drive and then prints out the response to the request to get the root directory listing in the drive.

To make the example code work below follow these steps to get the credentials file from Google API for your script:
  1. Log in to the google developer console.
  2. Go to the Drive API link under the Google Apps APIs
  3. Enable this API and download a credentials file
  4. From the credentials file take the installed json table and paste in a new file creds.json and place the file in the same directory as this demo file
  5. Now execute the code

Example code from demo.lua in the test subdirectory:
  1. local oauth2 = require 'oauth2'
  2. config = {
  3. auth_uri = 'https://accounts.google.com/o/oauth2/auth',
  4. token_url = 'https://accounts.google.com/o/oauth2/token',
  5.  
  6. approval_prompt = 'force',
  7. access_type = 'offline',
  8. scope = 'https://www.googleapis.com/auth/drive',
  9. creds_file = 'creds.json', -- Place the creds file if the file is used
  10. tokens_file = 'tokens.json', -- Where to save the tokens file
  11. }
  12.  
  13. oa,msg = oauth2.new(config)
  14. if oa then
  15. -- Acquire the token
  16. status, msg = oa:acquireToken()
  17. if status then
  18. -- Get the token from the user and give it to the object
  19. print("Go to the following URL and grant permissions and get the authorization code:")
  20. print(status[1])
  21. print("Enter the authorization code:")
  22. code = io.read()
  23. status,msg,content = status[2](code)
  24. if not status then
  25. print("Code authorization failed: "..msg,content)
  26. else
  27. print('Token acquired successfully.')
  28. -- Now try a request to get the root directory listing
  29. local url = 'https://www.googleapis.com/drive/v2/files/root?alt=json'
  30. resp, code = oa:request(url)
  31. if code < 200 or code > 206 then
  32. print("Error "..code)
  33. else
  34. print("Result:\n"..resp)
  35. end
  36. end
  37. else
  38. print("Error acquiring token "..msg)
  39. end
  40. else
  41. print("Error creating oAuth 2.0 object "..msg)
  42. end



API Reference


Module

API

The oauth2 module exposes just 1 function:

new

Syntax:
new((config: table)) -> (oauth2 Object: table)
To create a new oAuth 2.0 object.
Usage:
  1. oa,msg = new(config)

Inputs:
config table to configure the new oAuth 2.0 object. The configuration table can have the following keys:
  • creds_file: [OPTIONAL] Full path and name for the credentials file. This parameter if not given then the credentials must be provided in the creds table described below.
  • creds: [OPTIONAL] Table containing the connection credentials. This table must have the following keys:
    • client_id: String key for the client id.
    • client_secret: String key for the client secret.
    • redirect_uris: [OPTIONAL] Redirect URIs provided by the service
    • auth_uri or auth_url: [OPTIONAL] URL string for requesting authorization. NOTE: If this is given it will overwrite the auth_uri or auth_url given in the main config table
    • token_uri or token_url: [OPTIONAL] URL string for requesting token. NOTE: If this is given it will overwrite the token_uri or token_url given in the main config table
  • tokens_file: [OPTIONAL] Full path and name for the tokens file. This file will be used to read the token and save the updated token. NOTE: If both the tokens_file and tokens table have valid tokens then the tokens_file token is used.
  • tokens: [OPTIONAL] Table containing the access tokens for the oAuth object. This table must have the following keys:
    • access_token
    • token_type
    • refresh_token
    • expires
  • scope: Scope of the access
  • access_type: [OPTIONAL] The access_type parameter to be inserted in the query parameter of the endpoint
  • redirect_uri: [OPTIONAL] The redirect_uri parameter to be inserted in the query parameter of the endpoint
  • approval_prompt: [OPTIONAL] The approval_prompt parameter to be inserted in the query parameter of the endpoint
NOTE: Only the creds_file or creds keys are required for the connection to work.

Returns:
  • oAuth2.0 access object on success
  • nil and an error message on failure

oAuth 2.0 object


API

acquireToken

Syntax:
acquireToken((oauth2 object: table)) -> (Function table: table)
To acquire a access token for a oAuth 2.0 object
Usage:
  1. status,msg = oa:acquireToken()


Inputs:
  • oa: The oAuth 2.0 object

Returns:
  • nil and an error message on failure
  • table containing URL string and token add function - The URL string is the URL to follow to obtain the token code from the online service. The second return is a function that needs to be called once the code is obtained by passing the code to the function to finish acquiring the token

request

Syntax:
request((oauth2 object: table),(url: string)[, (payload: string or table)][,(headers: table)][,(verb: string)])
                             -> (response: string), (https response code: number), (token update flag: boolean)
To carry out a https request through the oAuth 2.0 protocol

Usage:
  1. status,msg = oa:request(url,payload,headers,verb)


Inputs:
  • oa: The oAuth 2.0 object
  • url: The url where to make the request
  • payload: [OPTIONAL] Data to post to the URL. This can be a string or a table. The function implementation of this is not implemented yet so that we can have a source function to stream data.
  • headers: [OPTIONAL] Table of headers to send the URL
  • verb: [OPTIONAL] The https request verb. Default is GET. If there is a payload then default is POST.

Returns:
  • nil and an error message on failure
  • The response as a string, the https response code and a boolean flag which is true if the token was refreshed on success request completion

Objects

creds

This is a table containing all the credentials for accessing the service. The keys in this table are the same as the creds table keys described in the config object input to the new function.

config

This table contains all the configuration parameters of the oAuth 2.0 object. This table structure is the same as the config structure described in the config object input to the new function.

tokens

Once the token is acquired then this table contains all the token information for the connection. The table structure is the same as the tokens table keys described in the config object input to the new function.

Credits

Thanks to the lua-basic-oauth2 repository in providing guidance on writing the oAuth 2.0 protocol for this module.