Getting Started with Number Verification API
Published on June 25, 2024

Introduction

This blog post will help you understand the Number Verification API and guide you through making your first API integration using a sample app written in node. Please note that this API is currently in beta, so some features may change as we continue to improve it.

What is the Number Verification API?

The Number Verification API verifies the phone number linked to the SIM card in the device connected to the mobile data network. This offers developers a secure possession factor to authenticate their end-users seamlessly. 

This authentication method is called Silent Authentication, as it happens in the background without the user's awareness. It improves the user experience by reducing the need for repeated logins and One-Time Passwords (OTP), especially in scenarios where the user is already logged in to a service or system.

Number Verification API is one of Vonage’s Network APIs, a new collection of APIs based on the CAMARA standard that exposes the network capabilities of mobile carriers (e.g., Telefonica, Deutsche Telekom, or Vodafone) to developers. These mobile carriers are also known as Communication Service Providers or CSPs.

Why Number Verification API?

Number Verification API improves service security by simplifying user authentication. It removes the need for extra mechanisms, such as one-time passwords (OTP) over SMS, Voice, or email.

There are some key benefits of using silent authentication:

  • The authentication is done “behind the scenes,” which means it does not interrupt the rest of the authentication process as it is transparent for the users.

  • The authentication is “silent”, removing the need for end-users to retrieve OTPs from a separate application.

  • It removes the exposure to toll fraud for developers, typically present with SMS and Voice OTP scenarios.

Current Limitations

Although silent authentication offers many benefits and improves the user experience, it does have some known drawbacks:

  • It only works when the mobile phone is connected to the data network. The developer needs to disable any WiFi connection and force traffic over the mobile network.

  • Coverage is limited. We are working on increasing the API coverage. In the meantime, feel free to contact us to learn about the next countries to support the Number Verification API.

Prerequisites

To follow this tutorial and make your first API call, you’ll need the following:

Create a New Application

Let’s start by creating a new application with the capabilities of the Network APIs.

Log in to your Vonage account and go to the dashboard. Then, go to “Applications” under the “Build & Manage” menu and click on the “Create a new application” button. Follow these steps:

  • Give a name to your application.

  • Click on “Generate public and private key,” as you’ll need this during the authentication process. A new public key will appear in the text box, and your browser will automatically download the private key file.

  • Under the capabilities section, enable “Network APIs” and select the business profile and the application profile you have previously created. Enter the URI that the Vonage auth system will call back during the first step of the authentication process. If you don’t know what to enter here, no worries. We’ll cover this in the next section of the tutorial.

Create New ApplicationCreate New Application

Once finished, click “Generate new application” and save the “Application ID” as you’ll need it during the authentication process.

Warning: Remember that application credentials are secret and for personal use only. Do not share them with anyone.

Making your First API Call

Authorization

Authorization is the process of granting a user or application access permissions to Vonage services and APIs. The Number Verification API requires implementing the oAuth2 authorization code flow on the backend side to generate an access token that will be used during the API call. 

The following steps describe how the Number Verification API auth flow works: 

Number Verification Authorization flowNumber Verification Authorization flow

  1. A user wants to log in to a mobile (or web) application using their mobile phone while connected to the data network. The application (front-end) sends an authorization request to the Vonage authorization server.

  2. The authorization server checks the client_id, the phone number, and the scope and redirects to the application’s backend with an authorization code. 

  3. The application backend exchanges the authorization code for an access token.

  4. A new access token is generated and returned.

  5. The application backend uses the access token to call the Number Verification API.

  6. The API response is received with a boolean value.

  7. The application backend answers the mobile app with the response.

Request Authorization Code

To request an authorization code, the application (frontend) must send a GET request to the Vonage /auth endpoint with the following query parameters:

  • client_id (required): corresponds to your Vonage Application ID. You can find it in your dashboard.

  • response_type (required): must be set to code as we implement authorization code.

  • scope (required): must be set to  openid dpv:FraudPreventionAndDetection#number-verification-verify-read

  • redirect_uri (required): The URI to redirect to after the user grants or denies permission. This URI must have been entered in the Redirect URI field of your Vonage application configuration (see Create New Application section above). The value of redirect_uri must match exactly with the value introduced in the application configuration, including upper or lower case, slashes and such.

  • login_hint (required): This field must be set to the phone number you wish to check, and it must include the international prefix.

  • state (required): A random string of at least 8 characters that serves as a unique identifier for each access token you generate. Think of it as a session ID for your authorization process. The backend must keep this state unique for each authorization request.

As soon as you implement this request, you’ll notice that the front-end lacks some of the abovementioned parameters. For instance, the redirect_uri, the scope, and the state are values managed exclusively by the backend.

One potential way to solve this is to request the request with all the needed parameters to the backend, as depicted in the following diagram:

Request Authorization Request exampleRequest Authorization Request example

The following JavaScript code example uses the express web framework to implement a login method to build the authorization request. This login method will be called by the client to initialize the whole
authorization flow:

app.get('/login, function(req, res) {

   const oidc_auth_uri = 'https://oidc.idp.vonage.com/oauth2/auth';

   // state could be any id associated with the user session 
  const state = generateRandomString(16);

  const redirect_uri = 'https://myserver.com/callback'
  const scope = 'openid dpv:FraudPreventionAndDetection#number-verification-verify-read'

  res.send(oidc_auth_uri + '?' +    
         querystring.stringify({      
               client_id: client_id,
               response_type: 'code'
               scope: scope,
               redirect_uri: redirect_uri,
              state: state,
              login_hint: phoneNumber
        }));
});

If everything goes well, the Vonage auth will redirect to the given redirect_uri (myserver.com/callback in the example above). The callback contains two query parameters:

  • Code (string) corresponds to the authorization code that can be exchanged for an access token.

  • State (string) contains the exact value of the state parameter supplied in the previous request.

For example:

https://mycompany.com/callback?code=EapDCg..B8W1Q&state=foobar

In case there is an error, the callback will contain the following query parameters:

  • error, which contains the reason why the authorization failed (e.g. server_error)

  • error_description, contains a human-readable description of the error.

Request an Access Token

Once our backend gets the callback from the Vonage auth server with a valid authorization code, it’s time to exchange it for an access token. To do so, you need to send a POST request to the /token endpoint with the following parameters encoded in application/x-www-form-urlencoded:

  • grant_type (required), must be set to authorization_code.

  • code (required), corresponds with the authorization code received in the callback from the previous step.

  • redirect_uri (required). This parameter is used for validation only as this step has no actual redirection. The value of this parameter must match the redirect_uri parameter from the previous step.

The request must contain the following HTTP headers:

  • Authorization. The value must be set to “Bearer “ + JWT token. You can generate a new token using our online JWT token generator.

  • Content-Type. This header must be set to “application/x-www-form-urlencoded”.

The following JavaScript example implements the exchange of the authorization code to request a new access token. For the sake of clarity, we have omitted sanity checks and error checking:

app.get('/callback', async function(req, res) {    

      const code = req.query.code; 
      const state = req.query.state;

      const camara_auth_uri = 'https://api-eu.vonage.com/oauth2/token';

      const data =
           code: code, 
           redirect_uri: 'https://myserver.com/callback'
           grant_type: 'authorization_code'


      const headers = {
         'Content-Type': 'application/x-www-form-urlencoded'
         'Authorization': 'Bearer ' + jwt
      }

     const response = await axios.post(camara_auth_uri, data, 
                                           { headers: headers});

     access_token = response.data.access_token;
});

On success, the response will contain a 200 OK status along with the following body represented in this example:

{ 
    "access_token": "<very_long_string>",
    "token_type": "Bearer",
    "expires_in": 3600,
}

Where:

  • access_token (string) contains the token we’ll use during the Number Verification API call.

  • token_type (string) will always contain the “Bearer” string.

  • expires_in (integer) specifies the expiration time of the token in minutes.

Calling Number Verification API 

The last step is to call the Number Verification API using the token you obtained in the previous step. 

According to the API reference, the API has one single endpoint /verify that supports only a POST operation with the following format:

  • The request body must be sent as “application/json” and should contain one element, phoneNumber, corresponding to the phone number (with the international prefix) you want to verify.

  • The request must contain the authorization header using the previously requested access token.

The following JavaScript code snippet implements the POST request to the /verify endpoint:

const uri = 'https://api-eu.vonage.com/camara/number-verification/v031/verify';

const data = JSON.stringify({ phoneNumber: phoneNumber });

const headers = {  
   'content-type': 'application/json',
   'Authorization': 'Bearer ' + access_token 
}

const response = await axios.post(uri, data, { headers: headers });

The response of the API will contain the verification of the phone number using a boolean value:

{ "devicePhoneNumberVerified": true }

What is next?

Once you receive the response from the Number Verification API, you can inform the user whether the authentication worked successfully. In that case, you could continue with the application's normal login flow or even implement more security measures on the client side if necessary.

Get in Touch

We’d love to hear from you! Join the Vonage Community Slack channel to share your experiences using the Number Verification API. You can also follow the Vonage Developer Experience team on X, formerly known as Twitter.

Alvaro NavarroSenior Developer Advocate

Alvaro is a developer advocate at Vonage, focusing on Network APIs. Passionate about Developer Experience, APIs, and Open Source. Outside work, you can often find him exploring comic shops, attending sci-fi and horror festivals or crafting stuff with those renowned tiny plastic building blocks.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.

Subscribe to Our Developer Newsletter

Subscribe to our monthly newsletter to receive our latest updates on tutorials, releases, and events. No spam.