Authentication

Application with a user interface

When developing an application with a user interface you will provide a way for the user to enter their email address and password in order for them login using your application and receive the access key and secret key binding required to authorize API requests.

This page provides an overview of the logic you should implement in your application to get the access key and secret key values required to authorize all requests to the API.

Programatically discover the correct base URL

Mimecast hosts data centers in many regions around the world. The region that a Mimecast account is hosted will dictate the API base URL that should be used for API requests. To prevent confusion the API provides a global function to programatically get the correct base url for any given user.

To use this function you send a request to https://api.mimecast.com/api/login/discover-authentication, for example:

POST https://api.mimecast.com/api/login/discover-authentication
x-mc-date: {dateTime}
x-mc-req-id: {unique id}
x-mc-app-id: {applicationId}
Content-Type: application/json
Accept: application/json

{
 "data": [
     {
         "emailAddress": "String"
     }
 ]
}
import uuid
import datetime
import requests

# Setup required variables
base_url = "https://api.mimecast.com"
uri = "/api/login/discover-authentication"
url = base_url + uri
app_id = "YOUR APPLICATION ID"

# Generate request header values
request_id = str(uuid.uuid4())
hdr_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"

# Create request headers
headers = {
    'x-mc-app-id': app_id,
    'x-mc-date': hdr_date,
    'x-mc-req-id': request_id,
    'Content-Type': 'application/json'
}

payload = {
 "data": [
     {
         "emailAddress": "String"
     }
 ]
}

r = requests.post(url=url, headers=headers, data=str(payload))

print r.text
static void Main(string[] args)
        {
            //Setup required variables
            string baseUrl = "https://api.mimecast.com";
            string uri = "/api/login/discover-authentication";
            string appId = "YOUR APPLICATION ID";

            //Generate request header values
            string hdrDate = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            //Add request body
            //Create and write data to stream
            string postData = @"{
                 ""data"": [
                     {
                         ""emailAddress"": ""String""
                     }
                 ]
                }";

            byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(payload, 0, payload.Length);
            stream.Close();

            //Send Request
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

            //Output response to console
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
            string responseBody = "";
            string temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                responseBody += temp;
            };
            System.Console.WriteLine(responseBody);
            System.Console.ReadLine();
        }
#Setup required variables
$baseUrl = "https://api.mimecast.com"
$uri = "/api/login/discover-authentication"
$url = $baseUrl + $uri
$appId = "YOUR APPLICATION ID"

#Generate request header values
$hdrDate = (Get-Date).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss UTC")
$requestId = [guid]::NewGuid().guid

#Create Headers
$headers = @{"x-mc-date" = $hdrDate;
                "x-mc-app-id" = $appId;
                "x-mc-req-id" = $requestId;
                "Content-Type" = "application/json"}

#Create post body
$postBody = "{
                 ""data"": [
                     {
                         ""emailAddress"": ""String""
                     }
                 ]
                }"

#Send Request
$response = Invoke-RestMethod -Method Post -Headers $headers -Body $postBody -Uri $url

#Print the response
$response
public static void main(String[] args) throws java.io.IOException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException {

        //set up variables for request
        String baseUrl = "https://api.mimecast.com";
        String uri = "/api/login/discover-authentication";
        String url = baseUrl + uri;
        String appId = "YOUR APPLICATION ID";

        //create URL object
        java.net.URL obj = new java.net.URL(url);

        // set guid for x-mc-req-id header
        String guid = java.util.UUID.randomUUID().toString();

        // set date for x-mc-date header
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        String date = sdf.format(new java.util.Date());

        // create request object
        javax.net.ssl.HttpsURLConnection con = (javax.net.ssl.HttpsURLConnection) obj.openConnection();

        //set request type to POST
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        //add reuqest headers
        con.setRequestProperty("x-mc-req-id", guid);
        con.setRequestProperty("x-mc-app-id", appId);
        con.setRequestProperty("x-mc-date", date);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        //Add post body to the request
        String postBody = "{\n" +
                " \"data\": [\n" +
                "     {\n" +
                "         \"emailAddress\": \"String\"\n" +
                "     }\n" +
                " ]\n" +
                "}";
        java.io.OutputStream os = con.getOutputStream();
        os.write(postBody.getBytes("UTF-8"));
        os.close();

        //process response
        java.io.BufferedReader in = new java.io.BufferedReader(
                new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //return result
        java.lang.System.out.println(response.toString());
    }

Where

  • the x-mc-app-id request header value is the Application ID provided when you registered for an application
  • emailAddress is the primary email address of the user you are attempting to discover.

The following is returned:

{
 "fail": [], 
 "meta": {
  "status": 200
 }, 
 "data": [
  {
   "region": {
    "api": "https://eu-api.mimecast.com", 
    "adminConsole": "https://console-uk.mimecast.com/mimecast/admin", 
    "code": "uk", 
    "name": "United Kingdom", 
    "mpp": "https://login-uk.mimecast.com"
   }, 
   "authenticate": [], 
   "emailAddress": "auser@mimecast.com", 
   "emailToken": "LOWgxk__TRUNCATED__nk2iIJc"
  }
 ]
}

The value of the "api" field in the object in the data array should be used as the base URL for all requests for the given user.

Login to get an access key and secret key binding

Login is the process of exchanging user credentials for an access key and secret key binding. To login, provide user inputs for email address, password, and the password type (either Cloud or Domain). Use these values in a request to /api/login/login. For example,

POST {base_url}/api/login/login
Authorization: Basic-Cloud {Base64 encoded emailAddress:password}
x-mc-date: {dateTime}
x-mc-req-id: {unique id}
x-mc-app-id {applicationId}
Content-Type: application/json
Accept: application/json

{
 "data": [
     {
         "userName": "String"
     }
 ]
}
import base64
import uuid
import datetime
import requests

# Setup required variables
base_url = "https://xx-api.mimecast.com"
uri = "/api/login/login"
url = base_url + uri
email_address = "THE USER'S EMAIL ADDRESS"
password = "THE USER'S PASSWORD"
app_id = "YOUR APPLICATION ID"
# Either Basic-Cloud for a Mimecast password or Basic-Ad for a domain password
auth_type = "Basic-Cloud"

# Generate request header values
request_id = str(uuid.uuid4())
hdr_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"

# Create request headers
headers = {
    'Authorization': auth_type + ' ' + base64.b64encode(email_address + ':' + password),
    'x-mc-app-id': app_id,
    'x-mc-date': hdr_date,
    'x-mc-req-id': request_id,
    'Content-Type': 'application/json'
}

payload = {
 "data": [
     {
         "userName": email_address
     }
 ]
}

r = requests.post(url=url, headers=headers, data=str(payload))

print r.text
static void Main(string[] args)
        {
            //Setup required variables
            string baseUrl = "https://xx-api.mimecast.com";
            string uri = "/api/login/login";
            string emailAddress = "THE USER'S EMAIL ADDRESS";
            string pass = "THE USER'S PASSWORD";
            string authType = "Basic-Cloud"; //Either Basic-Ad for domain password or Basic-Cloud for a Mimecast password 
            string appId = "YOUR APPLICATION ID";

            //Generate request header values
            string hdrDate = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = authType + " " + System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(emailAddress + ":" + pass));
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            //Add request body
            //Create and write data to stream
            string postData = @"{
                 ""data"": [
                     {
                         ""userName"": " + emailAddress + @"
                     }
                 ]
                }";

            byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(payload, 0, payload.Length);
            stream.Close();

            //Send Request
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

            //Output response to console
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
            string responseBody = "";
            string temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                responseBody += temp;
            };
            System.Console.WriteLine(responseBody);
            System.Console.ReadLine();
        }
#Setup required variables
$baseUrl = "https://xx-api.mimecast.com"
$uri = "/api/login/login"
$url = $baseUrl + $uri
$emailAddress = "THE USER'S EMAIL ADDRESS"
$pass = "THE USER'S PASSWORD"
$authType = "Basic-Cloud"; #Either Basic-Ad for domain password or Basic-Cloud for a Mimecast password 
$appId = "YOUR APPLICATION ID"

#Generate request header values
$hdrDate = (Get-Date).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss UTC")
$requestId = [guid]::NewGuid().guid

#Create Headers
$headers = @{"Authorization" = $authType + " " + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($emailAddress + ":" + $pass));
                "x-mc-date" = $hdrDate;
                "x-mc-app-id" = $appId;
                "x-mc-req-id" = $requestId;
                "Content-Type" = "application/json"}

#Create post body
$postBody = "{
                 ""data"": [
                     {
                         ""userName"": " + $emailAddress + "
                     }
                 ]
                }"

#Send Request
$response = Invoke-RestMethod -Method Post -Headers $headers -Body $postBody -Uri $url

#Print the response
$response
public static void main(String[] args) throws java.io.IOException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException {

        //set up variables for request
        String baseUrl = "https://xx-api.mimecast.com";
        String uri = "/api/login/login";
        String url = baseUrl + uri;
        String emailAddress = "THE USER'S EMAIL ADDRESS";
        String pass = "THE USER'S PASSWORD";
        String authType = "Basic-Cloud"; //Either Basic-Ad for domain password or Basic-Cloud for a Mimecast password 
        String appId = "YOUR APPLICATION ID";

        //create URL object
        java.net.URL obj = new java.net.URL(url);

        // set guid for x-mc-req-id header
        String guid = java.util.UUID.randomUUID().toString();

        // set date for x-mc-date header
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        String date = sdf.format(new java.util.Date());
		
		// base 64 encode the credentials
        String creds = emailAddress + ":" + pass;
        String base64creds = new String(org.apache.commons.codec.binary.Base64.encodeBase64(creds.getBytes()));

        // create request object
        javax.net.ssl.HttpsURLConnection con = (javax.net.ssl.HttpsURLConnection) obj.openConnection();

        //set request type to POST
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        //add reuqest headers
        con.setRequestProperty("Authorization", authType + " " + base64creds);
        con.setRequestProperty("x-mc-req-id", guid);
        con.setRequestProperty("x-mc-app-id", appId);
        con.setRequestProperty("x-mc-date", date);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        //Add post body to the request
        String postBody = "{\n" +
                " \"data\": [\n" +
                "     {\n" +
                "         \"userName\": " + emailAddress + "\n" +
                "     }\n" +
                " ]\n" +
                "}";
        java.io.OutputStream os = con.getOutputStream();
        os.write(postBody.getBytes("UTF-8"));
        os.close();

        //process response
        java.io.BufferedReader in = new java.io.BufferedReader(
                new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //return result
        java.lang.System.out.println(response.toString());
    }

The following is returned:

{
 "fail": [], 
 "meta": {
  "status": 200
 }, 
 "data": [
  {
   "username": "email address", 
   "bindingType": "one_step", 
   "accessKey": "RgOsq__TRUNCATED__JmliFkhE", 
   "extendOnValidate": false, 
   "secretKey": "trjUgREjhpVO__TRUNCATED__IwtPrPkw==", 
   "duration": 259200000, 
   "lastUserToken": "ntpdjMW8y-__TRUNCATED__utG3f22-Ow"
  }
 ]
}

Strore the accessKey and secretKey values to be used for future requests to the API.

Handle expired access key and secret key bindings

An access key and secret key binding has a time to live. This is defined by the Authentication Cache TTL setting in the user's effective Authentication Profile. If you make a request to the API using an expired binding you will receive 418 status code in response to your request. For exmaple,

418
{
   "meta": {
    "status": 418
    },
    "data": [
    ],
    "fail": [
       {
          "errors": [
             {
                "code": "err_xdk_binding_expired",
                "message": "0001 AccessKey Has Expired",
                "retryable": false
             }
          ]
       }
    ]
}

In this situation your application should refresh the binding by providing the API with the expired access key and re-authenticating the user. For example,

POST {base_url}/api/login/login
Authorization: Basic-Cloud {Base64 encoded emailAddress:password}
x-mc-date: {dateTime}
x-mc-req-id: {unique id}
x-mc-app-id {applicationId}
Content-Type: application/json
Accept: application/json

{
 "data": [
     {
         "userName": "email address",
         "accessKey": "access key"
     }
 ]
}
import base64
import uuid
import datetime
import requests

# Setup required variables
base_url = "https://xx-api.mimecast.com"
uri = "/api/login/login"
url = base_url + uri
email_address = "THE USER'S EMAIL ADDRESS"
password = "THE USER'S PASSWORD"
access_key = "THE EXPIRED ACCESS KEY"
app_id = "YOUR APPLICATION ID"
# Either Basic-Cloud for a Mimecast password or Basic-Ad for a domain password
auth_type = "Basic-Cloud"

# Generate request header values
request_id = str(uuid.uuid4())
hdr_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"

# Create request headers
headers = {
    'Authorization': auth_type + ' ' + base64.b64encode(email_address + ':' + password),
    'x-mc-app-id': app_id,
    'x-mc-date': hdr_date,
    'x-mc-req-id': request_id,
    'Content-Type': 'application/json'
}

payload = {
 "data": [
     {
         "userName": email_address,
         "accessKey": access_key
     }
 ]
}

r = requests.post(url=url, headers=headers, data=str(payload))

print r.text
static void Main(string[] args)
        {
            //Setup required variables
            string baseUrl = "https://xx-api.mimecast.com";
            string uri = "/api/login/login";
            string emailAddress = "THE USER'S EMAIL ADDRESS";
            string pass = "THE USER'S PASSWORD";
            string accessKey = "THE EXPIREDACCESS KEY";
            string authType = "Basic-Cloud"; //Either Basic-Ad for domain password or Basic-Cloud for a Mimecast password 
            string appId = "YOUR APPLICATION ID";

            //Generate request header values
            string hdrDate = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = authType + " " + System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(emailAddress + ":" + pass));
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            //Add request body
            //Create and write data to stream
            string postData = @"{
                 ""data"": [
                     {
                         ""userName"": " + emailAddress + @",
                         ""accessKey"": " + accessKey + @"
                     }
                 ]
                }";

            byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(payload, 0, payload.Length);
            stream.Close();

            //Send Request
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

            //Output response to console
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
            string responseBody = "";
            string temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                responseBody += temp;
            };
            System.Console.WriteLine(responseBody);
            System.Console.ReadLine();
        }
#Setup required variables
$baseUrl = "https://xx-api.mimecast.com"
$uri = "/api/login/login"
$url = $baseUrl + $uri
$emailAddress = "THE USER'S EMAIL ADDRESS"
$pass = "THE USER'S PASSWORD"
$accessKey = "THE EXPIRED ACCESS KEY"
$authType = "Basic-Cloud"; #Either Basic-Ad for domain password or Basic-Cloud for a Mimecast password 
$appId = "YOUR APPLICATION ID"

#Generate request header values
$hdrDate = (Get-Date).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss UTC")
$requestId = [guid]::NewGuid().guid

#Create Headers
$headers = @{"Authorization" = $authType + " " + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($emailAddress + ":" + $pass));
                "x-mc-date" = $hdrDate;
                "x-mc-app-id" = $appId;
                "x-mc-req-id" = $requestId;
                "Content-Type" = "application/json"}

#Create post body
$postBody = "{
                 ""data"": [
                     {
                         ""userName"": " + $emailAddress + ",
                         ""accessKey"": " + $accessKey + "
                     }
                 ]
                }"

#Send Request
$response = Invoke-RestMethod -Method Post -Headers $headers -Body $postBody -Uri $url

#Print the response
$response
public static void main(String[] args) throws java.io.IOException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException {

        //set up variables for request
        String baseUrl = "https://xx-api.mimecast.com";
        String uri = "/api/login/login";
        String url = baseUrl + uri;
        String emailAddress = "THE USER'S EMAIL ADDRESS";
        String pass = "THE USER'S PASSWORD";
        String accessKey = "THE EXPIRED ACCESS KEY";
        String authType = "Basic-Cloud"; //Either Basic-Ad for domain password or Basic-Cloud for a Mimecast password 
        String appId = "YOUR APPLICATION ID";

        //create URL object
        java.net.URL obj = new java.net.URL(url);

        // set guid for x-mc-req-id header
        String guid = java.util.UUID.randomUUID().toString();

        // set date for x-mc-date header
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        String date = sdf.format(new java.util.Date());
		
		// base 64 encode the credentials
        String creds = emailAddress + ":" + pass;
        String base64creds = new String(org.apache.commons.codec.binary.Base64.encodeBase64(creds.getBytes()));

        // create request object
        javax.net.ssl.HttpsURLConnection con = (javax.net.ssl.HttpsURLConnection) obj.openConnection();

        //set request type to POST
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        //add reuqest headers
        con.setRequestProperty("Authorization", authType + " " + base64creds);
        con.setRequestProperty("x-mc-req-id", guid);
        con.setRequestProperty("x-mc-app-id", appId);
        con.setRequestProperty("x-mc-date", date);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        //Add post body to the request
        String postBody = "{\n" +
                " \"data\": [\n" +
                "     {\n" +
                "         \"userName\": " + emailAddress + ",\n" +
                "         \"accessKey\": " + accessKey + "\n" +
                "     }\n" +
                " ]\n" +
                "}";
        java.io.OutputStream os = con.getOutputStream();
        os.write(postBody.getBytes("UTF-8"));
        os.close();

        //process response
        java.io.BufferedReader in = new java.io.BufferedReader(
                new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //return result
        java.lang.System.out.println(response.toString());
    }

On sucess, this will return the same response as the initial login and you will be able to successfully call the API again.

Provide a logout function

Mimecast limits the number of access key and secret key bindings that a user can have. Once the maximum is reached the user will no longer be able to use the API and you will need contact Mimecast support to request that the bindings are cleared. To prevent a build up of bindings the API provides a logout function that will remove the binding from Mimecast so it can no longer be used. To use the logout function you send an authorized request to the /api/login/logout endpoint. For example,

POST {base_url}/api/login/logout
Authorization: MC {accesskKey}:{Base64 encoded signed Data To Sign}
x-mc-date: {dateTime}
x-mc-req-id: {unique id}
x-mc-app-id {applicationId}
Content-Type: application/json
Accept: application/json

{
 "data": [
     {
         "accessKey": "THE ACCESS KEY TO DESTROY"
     }
 ]
}
import base64
import hashlib
import hmac
import uuid
import datetime
import requests

# Setup required variables
base_url = "https://xx-api.mimecast.com"
uri = "/api/login/logout"
url = base_url + uri
access_key = "YOUR ACCESS KEY"
secret_key = "YOUR SECRET KEY"
app_id = "YOUR APPLICATION ID"
app_key = "YOUR APPLICATION KEY"

# Generate request header values
request_id = str(uuid.uuid4())
hdr_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"

# Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
hmac_sha1 = hmac.new(secret_key.decode("base64"), ':'.join([hdr_date, request_id, uri, app_key]),
                  digestmod=hashlib.sha1).digest()

# Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
sig = base64.encodestring(hmac_sha1).rstrip()

# Create request headers
headers = {
    'Authorization': 'MC ' + access_key + ':' + sig,
    'x-mc-app-id': app_id,
    'x-mc-date': hdr_date,
    'x-mc-req-id': request_id,
    'Content-Type': 'application/json'
}

payload = {
 "data": [
     {
         "accessKey": "THE ACCESS KEY TO DESTROY"
     }
 ]
}

r = requests.post(url=url, headers=headers, data=str(payload))

print r.text
static void Main(string[] args)
        {
            //Setup required variables
            string baseUrl = "https://xx-api.mimecast.com";
            string uri = "/api/login/logout";
            string accessKey = "YOUR ACCESS KEY";
            string secretKey = "YOUR SECRET KEY";
            string appId = "YOUR APPLICATION ID";
            string appKey = "YOUR APPLICATION KEY";

            //Generate request header values
            string hdrDate = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
            System.Security.Cryptography.HMAC h = new System.Security.Cryptography.HMACSHA1(System.Convert.FromBase64String(secretKey));

            //Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
            byte[] hash = h.ComputeHash(System.Text.Encoding.Default.GetBytes(hdrDate + ":" + requestId + ":" + uri + ":" + appKey));

            //Build the signature to be included in the Authorization header in your request
            string signature = "MC " + accessKey + ":" + System.Convert.ToBase64String(hash);

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = signature;
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            //Add request body
            //Create and write data to stream
            string postData = @"{
                 ""data"": [
                     {
                         ""accessKey"": ""THE ACCESS KEY TO DESTROY""
                     }
                 ]
                }";

            byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(payload, 0, payload.Length);
            stream.Close();

            //Send Request
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

            //Output response to console
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
            string responseBody = "";
            string temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                responseBody += temp;
            };
            System.Console.WriteLine(responseBody);
            System.Console.ReadLine();
        }
#Setup required variables
$baseUrl = "https://xx-api.mimecast.com"
$uri = "/api/login/logout"
$url = $baseUrl + $uri
$accessKey = "YOUR ACCESS KEY"
$secretKey = "YOUR SECRET KEY"
$appId = "YOUR APPLICATION ID"
$appKey = "YOUR APPLICATION KEY"

#Generate request header values
$hdrDate = (Get-Date).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss UTC")
$requestId = [guid]::NewGuid().guid

#Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
$sha = New-Object System.Security.Cryptography.HMACSHA1
$sha.key = [Convert]::FromBase64String($secretKey)
$sig = $sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($hdrDate + ":" + $requestId + ":" + $uri + ":" + $appKey))
$sig = [Convert]::ToBase64String($sig)

#Create Headers
$headers = @{"Authorization" = "MC " + $accessKey + ":" + $sig;
                "x-mc-date" = $hdrDate;
                "x-mc-app-id" = $appId;
                "x-mc-req-id" = $requestId;
                "Content-Type" = "application/json"}

#Create post body
$postBody = "{
                 ""data"": [
                     {
                         ""accessKey"": ""THE ACCESS KEY TO DESTROY""
                     }
                 ]
                }"

#Send Request
$response = Invoke-RestMethod -Method Post -Headers $headers -Body $postBody -Uri $url

#Print the response
$response
public static void main(String[] args) throws java.io.IOException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException {

        //set up variables for request
        String baseUrl = "https://xx-api.mimecast.com";
        String uri = "/api/login/logout";
        String url = baseUrl + uri;
        String accessKey = "YOUR ACCESS KEY";
        String secretKey = "YOUR SECRET KEY";
        String appId = "YOUR APPLICATION ID";
        String appKey = "YOUR APPLICATION KEY";

        //create URL object
        java.net.URL obj = new java.net.URL(url);

        // set guid for x-mc-req-id header
        String guid = java.util.UUID.randomUUID().toString();

        // set date for x-mc-date header
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        String date = sdf.format(new java.util.Date());

        //create signature for the Authorization header
        String dataToSign = date + ":" + guid + ":" + uri + ":" + appKey;
        String hmacSHA1 = "HmacSHA1";
        javax.crypto.spec.SecretKeySpec signingKey = new javax.crypto.spec.SecretKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(secretKey.getBytes()), hmacSHA1);
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance(hmacSHA1);
        mac.init(signingKey);
        String sig = new String(org.apache.commons.codec.binary.Base64.encodeBase64(mac.doFinal(dataToSign.getBytes())));

        // create request object
        javax.net.ssl.HttpsURLConnection con = (javax.net.ssl.HttpsURLConnection) obj.openConnection();

        //set request type to POST
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        //add reuqest headers
        con.setRequestProperty("Authorization", "MC " + accessKey + ":" + sig);
        con.setRequestProperty("x-mc-req-id", guid);
        con.setRequestProperty("x-mc-app-id", appId);
        con.setRequestProperty("x-mc-date", date);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        //Add post body to the request
        String postBody = "{\n" +
                " \"data\": [\n" +
                "     {\n" +
                "         \"accessKey\": \"THE ACCESS KEY TO DESTROY\"\n" +
                "     }\n" +
                " ]\n" +
                "}";
        java.io.OutputStream os = con.getOutputStream();
        os.write(postBody.getBytes("UTF-8"));
        os.close();

        //process response
        java.io.BufferedReader in = new java.io.BufferedReader(
                new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //return result
        java.lang.System.out.println(response.toString());
    }

Handle the different user states

Where a login or refresh binding is not successful the status code returned is 401. A reason code is returned in an object in the errors array in the fail array of the response. The table below details expected error responses and the associated reasons. You should ensure that your application handles these responses.

ResponseMessageDescription
401
"errors": [
        {
          "code": "err_xdk_domain_not_managed",
          "message": "0003 Domain Not Managed On This Grid",
          "retryable": false
        }
      ]
The user's domain is not registered on the grid that the request is sent to.
401
"errors": [
        {
          "code": "err_xdk_invalid_credentials",
          "message": "0003 Invalid Credentials",
          "retryable": false
        }
      ]
The password is incorrect, the user is not recognized, the source IP address of the request is not permitted or the account has been disabled.
401
"errors": [
        {
          "code": "err_xdk_password_expired",
          "message": "0009 Password expired, change password",
          "retryable": false
        }
      ]
The user setting Force Change at Logon is enabled, or the cloud password has expired naturally.
401
"errors": [
        {
          "code": "err_xdk_locked",
          "message": "0010 Login Locked Out - Too Many Failures",
          "retryable": false
        }
      ]
The user account is locked.