Skip to contentSkip to navigationSkip to topbar
Page toolsOn this page
Looking for more inspiration?Visit the

Protect your Function with Basic Auth


(warning)

Runtime handler version requirement

This example uses headers and cookies, which are only accessible when your Function is running @twilio/runtime-handler version 1.2.0 or later. Consult the Runtime Handler guide to learn more about the latest version and how to update.

When protecting your public Functions, and any sensitive data that they can expose, from unwanted requests and bad actors, it is important to consider some form of authentication(link takes you to an external page) to validate that only intended users are making requests. In this example, we'll be covering one of the most common forms of authentication: Basic Authentication.

If you want to learn an alternative approach, you can also see this example of using JWT for authentication.

Let's create a Function that will only accept requests with valid Basic Authentication, and reject all other traffic.


Create and host a Function

create-and-host-a-function page anchor

Before you run any of the examples on this page, create a Function and paste the example code into it. You can create a Function in the Twilio Console or by using the Serverless Toolkit.

ConsoleServerless Toolkit

If you prefer a UI-driven approach, complete these steps in the Twilio Console:

  1. Log in to the Twilio Console(link takes you to an external page) and navigate to Develop > Functions & Assets. If you're using the legacy Console, open the Functions tab(link takes you to an external page).
  2. Functions are contained within Services. Click Create Service(link takes you to an external page) to create a new Service.
  3. Click Add + and select Add Function from the dropdown.
  4. The Console creates a new protected Function that you can rename. The filename becomes the URL path of the Function.
  5. Copy one of the example code snippets from this page and paste the code into your newly created Function. You can switch examples by using the dropdown menu in the code rail.
  6. Click Save.
  7. Click Deploy All to build and deploy the Function. After deployment, you can access your Function at https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world.

You can now invoke your Function with HTTP requests, configure it as the webhook for a Twilio phone number, call it from a Twilio Studio Run Function Widget, and more.

Authenticate Function requests using Basic Authorization

authenticate-function-requests-using-basic-authorization page anchor
1
exports.handler = (context, event, callback) => {
2
// For the purpose of this example, we'll assume that the username and
3
// password are hardcoded values. Feel free to set these as other values,
4
// or better yet, use environment variables instead!
5
const USERNAME = 'twilio';
6
const PASSWORD = 'ahoy!';
7
8
// Prepare a new Twilio response for the incoming request
9
const response = new Twilio.Response();
10
// Grab the standard HTTP Authorization header
11
const authHeader = event.request.headers.authorization;
12
13
// Reject requests that don't have an Authorization header
14
if (!authHeader) return callback(null, setUnauthorized(response));
15
16
// The auth type and credentials are separated by a space, split them
17
const [authType, credentials] = authHeader.split(' ');
18
// If the auth type doesn't match Basic, reject the request
19
if (authType.toLowerCase() !== 'basic')
20
return callback(null, setUnauthorized(response));
21
22
// The credentials are a base64 encoded string of 'username:password',
23
// decode and split them back into the username and password
24
const [username, password] = Buffer.from(credentials, 'base64')
25
.toString()
26
.split(':');
27
// If the username or password don't match the expected values, reject
28
if (username !== USERNAME || password !== PASSWORD)
29
return callback(null, setUnauthorized(response));
30
31
// If we've made it this far, the request is authorized!
32
// At this point, you could do whatever you want with the request.
33
// For this example, we'll just return a 200 OK response.
34
return callback(null, 'OK');
35
};
36
37
// Helper method to format the response as a 401 Unauthorized response
38
// with the appropriate headers and values
39
const setUnauthorized = (response) => {
40
response
41
.setBody('Unauthorized')
42
.setStatusCode(401)
43
.appendHeader(
44
'WWW-Authenticate',
45
'Basic realm="Authentication Required"'
46
);
47
48
return response;
49
};

Configure your Function to require Basic Authentication

configure-your-function-to-require-basic-authentication page anchor

First, create a new auth Service and add a Public /basic Function using the directions above.

Delete the default contents of the Function, and paste in the code snippet provided above.

Save the Function once it contains the new code.

(information)

Info

Remember to change the visibility of your new Function to be Public. By default, the Console UI will create new Functions as Protected, which will prevent access to your Function except by Twilio requests.

Next, deploy the Function by clicking on Deploy All in the Console UI.


Verify that Basic Authentication is working

verify-that-basic-authentication-is-working page anchor

We can check that authentication is working first by sending an unauthenticated request to our deployed Function. You can get the URL of your Function by clicking the Copy URL button next to the Function.

Then, using your client of choice, make a GET or POST request to your Function. It should return a 401 Unauthorized since the request contains no valid Authorization header.

curl -i -L -X POST 'https://auth-4173-dev.twil.io/basic'

Result:

1
$ curl -i -L -X POST 'https://auth-4173-dev.twil.io/basic'
2
3
HTTP/2 401
4
date: Tue, 03 Aug 2021 21:55:02 GMT
5
content-type: application/octet-stream
6
content-length: 12
7
www-authenticate: Basic realm="Authentication Required"
8
x-shenanigans: none
9
10
Unauthorized

Great! Requests are successfully being blocked from non-authenticated requests.

To make an authenticated request and get back a 200 OK, we'll need to generate and send a request with the example username and password encoded as the Authorization header credentials. Leverage one of the following methods to encode your Credentials:

Browser Dev ToolsNode.js REPL

First, open your browser's developer tools(link takes you to an external page). Navigate to the Console tab, where you'll be able to execute the following JavaScript in the browser to generate your encoded credentials:

btoa("<username>:<password>");

The btoa method(link takes you to an external page) is a built-in browser method for conveniently converting a string to base64 encoding.

For example, with our example credentials, you would input the following into the browser console and get this result:

1
btoa("twilio:ahoy!")
2
> "dHdpbGlvOmFob3kh"

Now that you have your encoded credentials, it's time to make an authenticated request to your Function by including them in the Authentication header.

Using cURL with our example credentials would look like this:

1
curl -i -L -X POST 'https://auth-4173-dev.twil.io/basic' \
2
-H 'Authorization: Basic dHdpbGlvOmFob3kh'
3

and the response would be:

1
$ curl -i -L -X POST 'https://auth-4173-dev.twil.io/basic' \
2
-H 'Authorization: Basic dHdpbGlvOmFob3kh'
3
4
HTTP/2 200
5
date: Tue, 03 Aug 2021 22:15:37 GMT
6
content-type: text/plain; charset=utf8
7
content-length: 2
8
x-shenanigans: none
9
x-content-type-options: nosniff
10
x-xss-protection: 1; mode=block
11
12
OK

At this point, Basic Authentication is now working for your Function!

To make this example your own, you could experiment with:

  • Instead of defining the username and password directly in your Function's code, define other secure values and store them securely as Environment Variables. You could then access them using context.USERNAME and context.PASSWORD respectively, for example.
  • Take things a bit further and establish a database of authenticated users with hashed passwords. Once you've retrieved the decoded username and password from the Authorization header, perform a lookup of the user by username and validate their password using a library such as bcrypt(link takes you to an external page). Your hashing secret can be a secure Environment Variable.