Skip to contentSkip to navigationSkip to topbar
Rate this Page:

Protect your Function with Basic Auth


(warning)

Warning

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

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page) . If you need an account, you can sign up for a free Twilio account here(link takes you to an external page) !
  2. Functions are contained within Services . Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function .
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world .

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!

Authenticate Function requests using Basic Authorization

authenticate-function-requests-using-basic-authorization page anchor

_49
exports.handler = (context, event, callback) => {
_49
// For the purpose of this example, we'll assume that the username and
_49
// password are hardcoded values. Feel free to set these as other values,
_49
// or better yet, use environment variables instead!
_49
const USERNAME = 'twilio';
_49
const PASSWORD = 'ahoy!';
_49
_49
// Prepare a new Twilio response for the incoming request
_49
const response = new Twilio.Response();
_49
// Grab the standard HTTP Authorization header
_49
const authHeader = event.request.headers.authorization;
_49
_49
// Reject requests that don't have an Authorization header
_49
if (!authHeader) return callback(null, setUnauthorized(response));
_49
_49
// The auth type and credentials are separated by a space, split them
_49
const [authType, credentials] = authHeader.split(' ');
_49
// If the auth type doesn't match Basic, reject the request
_49
if (authType.toLowerCase() !== 'basic')
_49
return callback(null, setUnauthorized(response));
_49
_49
// The credentials are a base64 encoded string of 'username:password',
_49
// decode and split them back into the username and password
_49
const [username, password] = Buffer.from(credentials, 'base64')
_49
.toString()
_49
.split(':');
_49
// If the username or password don't match the expected values, reject
_49
if (username !== USERNAME || password !== PASSWORD)
_49
return callback(null, setUnauthorized(response));
_49
_49
// If we've made it this far, the request is authorized!
_49
// At this point, you could do whatever you want with the request.
_49
// For this example, we'll just return a 200 OK response.
_49
return callback(null, 'OK');
_49
};
_49
_49
// Helper method to format the response as a 401 Unauthorized response
_49
// with the appropriate headers and values
_49
const setUnauthorized = (response) => {
_49
response
_49
.setBody('Unauthorized')
_49
.setStatusCode(401)
_49
.appendHeader(
_49
'WWW-Authenticate',
_49
'Basic realm="Authentication Required"'
_49
);
_49
_49
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.


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

Result:


_10
$ curl -i -L -X POST 'https://auth-4173-dev.twil.io/basic'
_10
_10
HTTP/2 401
_10
date: Tue, 03 Aug 2021 21:55:02 GMT
_10
content-type: application/octet-stream
_10
content-length: 12
_10
www-authenticate: Basic realm="Authentication Required"
_10
x-shenanigans: none
_10
_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:


_10
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:


_10
btoa("twilio:ahoy!")
_10
> "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:


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

and the response would be:


_12
$ curl -i -L -X POST 'https://auth-4173-dev.twil.io/basic' \
_12
-H 'Authorization: Basic dHdpbGlvOmFob3kh'
_12
_12
HTTP/2 200
_12
date: Tue, 03 Aug 2021 22:15:37 GMT
_12
content-type: text/plain; charset=utf8
_12
content-length: 2
_12
x-shenanigans: none
_12
x-content-type-options: nosniff
_12
x-xss-protection: 1; mode=block
_12
_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.

Rate this Page: