Documentation

Auth API

The Auth API is a low-level, RESTful API for adding strong two-factor authentication to your website or application. Check out the Two-Factor Authentication for SaaS Apps Solution Guide for an Auth API tutorial.

First Steps

Before starting:

  1. Sign up for a Duo account
  2. Create a new Auth API integration. This will generate an integration key, secret key, and API hostname for you to use. (See Getting Started for help.)

Duo Security has demonstration clients available on Github to call the Duo API methods. Examples are available in: Python, Java, C#, Ruby, and Perl.

Connectivity Requirements

This integration communicates with Duo’s service on TCP port 443. Also, we do not recommend locking down your firewall to individual IP addresses, since these may change over time to maintain our service’s high availability.

Endpoints

/ping

The /ping endpoint acts as a “liveness check” that can be called to verify that Duo is up before trying to call other endpoints. Unlike the other endpoints, this one does not have to be signed with the Authorization header.

GET /auth/v2/ping

Parameters

None.

Response Codes

Response Meaning
200 Success.

Response Format

Key Value
time Current server time. Formatted as a UNIX timestamp. Integer.

Example Response

{
  "stat": "OK",
  "response": {
    "time": 1357020061
  }
}

/check

The /check endpoint can be called to verify that the integration and secret keys are valid, and that the signature is being generated properly.

GET /auth/v2/check

Parameters

None required.

Response Codes

Response Meaning
200 Success.
401 The "Authorization" and/or "Date" headers were missing or invalid.

Response Format

Key Value
time Current server time. Formatted as a UNIX timestamp. Integer.

Example Response

{
  "stat": "OK",
  "response": {
    "time": 1357020061
  }
}

/logo

The /logo endpoint provides a programmatic way to retrieve your stored logo.

GET /auth/v2/logo

Parameters

None required.

Response Codes

Response Meaning
200 Success.
404 No logo was found.

Response Format

On success, the response body is Content-Type image/png, containing the logo.

On failure, the response is the standard error JSON.

/enroll

The /enroll endpoint provides a programmatic way to enroll new users with Duo two-factor authentication. It returns a code (as a barcode image) that Duo Mobile can scan with its built-in camera. This adds the user’s account to the app so that they receive and respond to Duo Push login requests.

POST /auth/v2/enroll

Parameters

Parameter Required? Description
username Optional Username for the created user. If not given, a random username will be assigned and returned.
valid_secs Optional Seconds for which the activation code will remain valid. Default: 86400 (one day).

Response Codes

Response Meaning
200 Success.
400 Invalid or missing parameters, or a user with username already exists.

Response Format

Key Value
activation_barcode URL for an image of a scannable barcode with the activation code.
activation_code Code to enter into the Duo Mobile app to add the account. On phones with Duo Mobile already installed it will be a clickable link, so this link
expiration Time at which this activation code will expire. Formatted as a UNIX timestamp. Integer.
user_id Permanent, unique identifier for the user in Duo. Always generated.
username Unique name for the user in Duo. Either specified as a parameter or auto-generated.

Example Response

{
  "stat": "OK",
  "response": {
    "activation_barcode": "https://api-eval.duosecurity.com/frame/qr?value=8LIRa5danrICkhHtkLxi-cKLu2DWzDYCmBwBHY2YzW5ZYnYaRxA",
    "activation_code": "duo://8LIRa5danrICkhHtkLxi-cKLu2DWzDYCmBwBHY2YzW5ZYnYaRxA",
    "expiration": 1357020061,
    "user_id": "DU94SWSN4ADHHJHF2HXT",
    "username": "49c6c3097adb386048c84354d82ea63d"
  }
}

/enroll_status

Check whether a user has completed enrollment.

POST /auth/v2/enroll_status

Parameters

Parameter Required? Description
user_id Required ID of the user.
activation_code Required Activation code, as returned from /enroll.

Response Codes

Response Meaning
200 Success.
400 Invalid or missing parameters.

Response Format

One of the following strings:

Value Meaning
success The user successfully added the account to Duo Mobile.
invalid The code is expired or otherwise not valid for the specified user.
waiting The code has not been claimed yet.

Example Response

{
  "stat": "OK",
  "response": "success"
}

/preauth

The /preauth endpoint determines whether a user is authorized to log in, and (if so) returns the user’s available authentication factors.

POST /auth/v2/preauth

Parameters

Param Required? Description
ipaddr Optional The IP address of the user to be authenticated, in dotted quad format. This will cause an “allow” response to be sent if appropriate for requests from a trusted network.
user_id Required if username is not specified ID of the user. Exactly one of user_id and username must be specified.
username Required if user_id is not specified Username of the user to check. Exactly one of user_id and username must be specified.
trusted_device_token Optional If the trusted_device_token is present and the Trusted devices option is enabled in the Duo admin interface, return an “allow” response for the period of time a device may be remembered as set by the Duo administrator.

Response Codes

Response Meaning
200 Success.
400 Invalid or missing parameters.

Response Format

Key Value
result One of the following strings:
Value Meaning
auth The user is known and permitted to authenticate. Your client application should use the /auth endpoint to perform authentication.
allow The user is configured to bypass secondary authentication. Your client application should immediately grant access.
deny The user is not permitted to authenticate at this time. Your client application should immediately deny access.
enroll The user is not known to Duo and needs to enroll. Your application should deny access.
status_msg

Human-readable message describing the result. This string is intended for display to the user.

devices

A list of the user’s devices, where each device is a series of key/value pairs.

This field will only be present if result is "auth".

Key Value
capabilities List of strings, each a factor that can be used with the device.
Capability Meaning
push The device is activated for Duo Push.
phone The device can receive phone calls.
sms The device can receive batches of SMS passcodes.
device Identifies which of the user’s devices this is.
display_name A short string which can be used to identify the device in a prompt.
name Device’s name. Or, if the device has not been named, the empty string ("").
next_sms_passcode Starting letter of the next acceptable passcode previously SMSed to the user, if any.

This field will only be present if the device has the "sms" capability and has previously received passcodes.

number Masked phone number of the device. Or, If the device has no associated number, the empty string ("").
type "phone", "token", or "desktoptoken".
enroll_portal_url

If result is "enroll" a unique, enrollment portal URL is returned. This URL may be passed to the user and opened in a new browser window to access a portal that will help the user associate a device with the user_id specified or returned when calling /preauth.

This enrollment portal URL should be used instead of calling /enroll if your users need to enroll phones that are not capable of running Duo Mobile, such as landlines or cell phones. /enroll only supports enrolling smartphones that can run Duo Mobile.

This field will only be present if result is "enroll".

Example Responses

If result was "auth":

{
  "stat": "OK",
  "response": {
    "result": "auth",
    "status_msg": "Account is active",
    "devices": [
      {
        "device": "DPFZRS9FB0D46QFTM891",
        "type": "phone",
        "number": "XXX-XXX-0100",
        "name": "",
        "capabilities": [
            "push",
            "sms",
            "phone"
        ]
      },
      {
        "device": "DHEKH0JJIYC1LX3AZWO4",
        "type": "token",
        "name": "0"
      }
    ]
  }
}

If result was "enroll":

{
  "stat": "OK",
  "response": {
    "enroll_portal_url": "https://api-3945ef22.duosecurity.com/portal?48bac5d9393fb2c2", 
    "result": "enroll",
    "status_msg": "Enroll an authentication device to proceed"
  }
}

/auth

The /auth endpoint performs second-factor authentication for a user by sending a push notification to the user’s smartphone app, verifying a passcode, or placing a phone call. It is also used to send the user a new batch of passcodes via SMS.

POST /auth/v2/auth

Parameters

Param Required? Description
user_id Required if username is not specified ID of the user. Exactly one of user_id and username must be specified.
username Required if user_id is not specified Username of the user. Exactly one of user_id and username must be specified.
factor Required Factor to use for authentication. Currently, the following choices are supported:
Value Meaning
auto Use the out-of-band factor (push or phone) recommended by Duo as the best for the user’s devices.
push Authenticate the user with Duo Push.
passcode Authenticate the user with a passcode (from Duo Mobile, SMS, hardware token, or bypass code).
sms Send a new batch of SMS passcodes to the user. Note that this will not actually authenticate the user (it will automatically return “deny”). Thus, if the user elects to do this then you should re-prompt to authenticate after the call has completed.
phone Authenticate the user with phone callback.

Also see below for additional parameters that are necessary depending on the factor you specify.

ipaddr Optional The IP address of the user to be authenticated, in dotted quad format. This will cause an “allow” response to be sent if appropriate for requests from a trusted network.
async Optional

If this parameter is not provided, then the /auth endpoint will only return a response when the authentication process has completed. If, however, your application provides this parameter with a value of “1”, then /auth will immediately return a transaction ID, and your application will need to subsequently query the /auth_status endpoint to get the status (and, eventually, result) of the authentication process.

If you enable async, then your application will be able to retrieve real-time status updates from the authentication process, rather than receiving no information until the process is complete.

Additionally, you will need to pass some factor-specific parameters depending on the authentication method.

Duo Push

Parameter Required? Description
device Required

ID of the device. This device must have the "push" capability.

You may also specify "auto" to use the first of the user’s devices with the "push" capability.

type Optional This string is displayed in the Duo Mobile app before the word “request”. The default is “Login”, so the phrase “Login request” appears in the push notification text and on the request details screen. You may want to specify “Transaction”, “Transfer”, etc.
display_username Optional String to display in Duo Mobile in place of the user’s Duo username.
pushinfo Optional

A set of URL-encoded key/value pairs with additional contextual information associated with this authentication attempt. The Duo Mobile app will display this information to the user.

For example: from=login%20portal&domain=example.com

Passcode

Parameter Required? Description
passcode Required Passcode entered by the user.

Phone callback

Parameter Required? Description
device Required

ID of the device to call. This device must have the "phone" capability.

You may also specify "auto" to use the first of the user’s devices with the "phone" capability.

Sending new SMS passcodes

Parameter Required? Description
device Required

ID of the device to send passcodes to. This device must have the "sms" capability.

You may also specify "auto" to use the first of the user’s devices with the "sms" capability.

The response will be returned in the container format described above. For successful responses, the payload will contain the following key/value pairs:

Response Codes

Response Meaning
200 Success.
400 Invalid or missing parameters. For example, the user does not exist or does not have any device capable of performing the requested authentication.

Response formats

If async was not enabled:

Key Value
result Either “allow” or “deny”. If “allow” was returned, your application should grant access to the user. If “deny”, it should not.
status String detailing the progress or outcome of the authentication attempt. Use the result response to decide whether to grant access or not.
status_msg A string describing the result of the authentication attempt. If the authentication attempt was denied, it may identify a reason. This string is intended for display to the user.
trusted_device_token Returns a string containing a token for that trusted device, which can be passed into the /preauth endpoint. Requires the Trusted devices option enabled in the Duo admin interface.

If async was enabled:

Key Value
txid A transaction ID to be used to query the authentication status using the /auth_status endpoint.

Example Responses

If async was not enabled:

{
  "stat": "OK",
  "response": {
    "result": "allow",
    "status": "allow",
    "status_msg": "Success. Logging you in..."
  }
}

If async was enabled:

{
  "stat": "OK",
  "response": {
    "txid": "45f7c92b-f45f-4862-8545-e0f58e78075a"
  }
}

/auth_status

The /auth_status endpoint “long-polls” for the next status update from the authentication process for a given transaction. That is to say, if no status update is available at the time the request is sent, it will wait until there is an update before returning a response.

GET /auth/v2/auth_status

Parameters

Param Required? Description
txid Required The transaction ID of the authentication attempt, as returned by the /auth endpoint.

Response Codes

Response Meaning
200 Success.
400 Invalid or missing parameters.

Response Format

Key Value
result One of the following values:
Value Meaning
allow Authentication succeeded. Your application should grant access to the user.
deny Authentication denied. Your application should deny access.
waiting Authentication is still in-progress. Your application should poll again until it finishes. Check the status for more details on the progress.
trusted_device_token When /auth is used with async enabled, returns a string containing a token for that trusted device, which can be passed into the /preauth endpoint. Requires the Trusted devices option enabled in the Duo admin interface.
status String detailing the progress or outcome of the authentication attempt.
Value Meaning
calling Currently calling the user’s phone. The result will be “waiting”.
answered Phone call answered. The result will be “waiting”.
pushed A Duo Push authentication request has been sent to the device. The result will be “waiting”.
push_failed An error occurred while sending the push notification to the user’s device. The user should retrieve the request manually using the Duo Push button in the Duo Mobile app. The result will be “waiting”.
timeout Authentication timed out. Duo Push times out after 60 seconds and phone calls will also time out after approximately one minute. The result will be “waiting”.
fraud The authentication request was reported as fraudulent. The result will be “deny”.
allow Authentication succeeded. The result will be “allow”.
bypass Authentication has been skipped for a user in bypass mode. The result will be “allow”.
deny Authentication denied. The result will be “deny”.
locked_out The user has been disabled due to authentication failures. The result will be “deny”.
sent Passcodes have been sent to the device. The result will be “deny”.
status_msg Human-readable string describing the status of the authentication attempt. If the authentication attempt was denied, it may identify a reason. This string is intended for display to the user.

Example Response

{
  "stat": "OK",
  "response": {
    "result": "waiting",
    "status": "pushed",
    "status_msg": "Pushed a login request to your phone..."
  }
}

API Details

Base URL

All API methods use your API hostname, https://api-XXXXXXXX.duosecurity.com.

Methods always use HTTPS. Unsecured HTTP is not supported.

Request Format

All requests must have “Authorization” and “Date” headers.

If the request method is GET or DELETE, URL-encode parameters and send them in the URL query string like this: /accounts/v1/account/list?realname=First%20Last&username=root. They still go on a separate line when creating the string to sign for an Authorization header.

Send parameters for POST requests in the body as URL-encoded key-value pairs (the same request format used by browsers to submit form data). The header “Content-Type: application/x-www-form-urlencoded” must also be present.

When URL-encoding, all bytes except ASCII letters, digits, underscore (“_”), period (“.”), tilde (“~”), and hyphen (“-“) are replaced by a percent sign (“%”) followed by two hexadecimal digits containing the value of the byte. For example, a space is replaced with “%20” and an at-sign (“@”) becomes “%40”. Use only upper-case A through F for hexadecimal digits.

Response Format

Responses are formatted as a JSON object with a top-level stat key.

Successful responses will have a stat value of “OK” and a response key. The response will either be a single object or a sequence of other JSON types, depending on which endpoint is called.

{
  "stat": "OK",
  "response": {
    "key": "value"
  }
}

Values are returned as strings unless otherwise documented.

Unsuccessful responses will have a stat value of “FAIL”, an integer code, and a message key that further describes the failure. A message_detail key may be present if additional information is available (like the specific parameter that caused the error).

{
  "stat": "FAIL",
  "code": 40002,
  "message": "Invalid request parameters",
  "message_detail": "username"
}

The HTTP response code will be the first three digits of the more specific code found inside the JSON object. Each endpoint’s documentation lists HTTP response codes it can return. Additionally, all API endpoints that require a signed request can return the following HTTP response codes:

Response Meaning
200 The request completed successfully.
401 The “Authorization”, “Date”, and/or “Content-Type” headers were missing or invalid.
403

This integration is not authorized for this endpoint or the ikey was created for a different integration type (for example, using an Auth API ikey with Admin API endpoints).

405 The request’s HTTP verb is not valid for this endpoint (for example, POST when only GET is supported).

Authentication

The API uses HTTP Basic Authentication to authenticate requests. Use your integration’s integration key as the HTTP Username.

Generate the HTTP Password as an HMAC signature of the request. This will be different for each request and must be re-generated each time.

To construct the signature, first build an ASCII string from your request, using the following components:

Component Description Example
date The current time, formatted as RFC 2822. This must be the same string as the “Date” header. Tue, 21 Aug 2012 17:29:18 -0000
method The HTTP method (uppercase) POST
host Your API hostname (lowercase) api-xxxxxxxx.duosecurity.com
path

The specific API method’s path

/accounts/v1/account/list
params The URL-encoded list of key=value pairs, lexicographically sorted by key. These come from the request parameters (the URL query string for GET and DELETE requests or the request body for POST requests). If the request does not have any parameters one must still include a blank line in the string that is signed. Do not encode unreserved characters. Use upper-case hexadecimal digits A through F in escape sequences. realname=First%20Last&username=root

Then concatenate these components with (line feed) newlines. For example:

Tue, 21 Aug 2012 17:29:18 -0000
POST
api-xxxxxxxx.duosecurity.com
/accounts/v1/account/list
realname=First%20Last&username=root

GET requests also use this five-line format:

Tue, 21 Aug 2012 17:29:18 -0000
GET
api-xxxxxxxx.duosecurity.com
/accounts/v1/account/list
username=root

Lastly, compute the HMAC-SHA1 of this canonical representation, using your integration’s secret key as the HMAC key. Send this signature as hexadecimal ASCII (i.e. not raw binary data). Use HTTP Basic Authentication for the request, using your integration key as the username and the HMAC-SHA1 signature as the password.

For example, here are the headers for the above POST request to api-XXXXXXXX.duosecurity.com/accounts/v1/account/list, using DIWJ8X6AEYOR5OMC6TQ1 as the integration key and Zh5eGmUq9zpfQnyUIu5OL9iWoMMv5ZNmk3zLJ4Ep as the secret key:

Date: Tue, 21 Aug 2012 17:29:18 -0000
Authorization: Basic RElXSjhYNkFFWU9SNU9NQzZUUTE6MmQ5N2Q2MTY2MzE5NzgxYjVhM2EwN2FmMzlkMzY2ZjQ5MTIzNGVkYw==
Host: api-XXXXXXXX.duosecurity.com
Content-Length: 35
Content-Type: application/x-www-form-urlencoded

Separate HTTP request header lines CRLF newlines.

The following Python function can be used to construct the “Authorization” and “Date” headers:

import base64, email, hmac, hashlib, urllib

def sign(method, host, path, params, skey, ikey):
    """
    Return HTTP Basic Authentication ("Authorization" and "Date") headers.
    method, host, path: strings from request
    params: dict of request parameters
    skey: secret key
    ikey: integration key
    """

    # create canonical string
    now = email.Utils.formatdate()
    canon = [now, method.upper(), host.lower(), path]
    args = []
    for key in sorted(params.keys()):
        val = params[key]
        if isinstance(val, unicode):
            val = val.encode("utf-8")
        args.append(
            '%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~')))
    canon.append('&'.join(args))
    canon = '\n'.join(canon)

    # sign canonical string
    sig = hmac.new(skey, canon, hashlib.sha1)
    auth = '%s:%s' % (ikey, sig.hexdigest())

    # return headers
    return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}