

# Authentication
<a name="authentication"></a>

Authentication is a mechanism where you verify the identity of a client or a server. Server authentication is the process where devices or other clients ensure they are communicating with an actual AWS IoT endpoint. Client authentication is the process where devices or other clients authenticate themselves with AWS IoT. 

## X.509 Certificate overview
<a name="x509-certificate-overview"></a>

X.509 certificates are digital certificates that use the [X.509 public key infrastructure standard](https://en.wikipedia.org/wiki/X.509) to associate a public key with an identity contained in a certificate. X.509 certificates are issued by a trusted entity called a certification authority (CA). The CA maintains one or more special certificates called CA certificates that it uses to issue X.509 certificates. Only the certification authority has access to CA certificates. X.509 certificate chains are used both for server authentication by clients and client authentication by the server.

# Server authentication
<a name="server-authentication"></a>

When your device or other client attempts to connect to AWS IoT Core, the AWS IoT Core server will send an X.509 certificate that your device uses to authenticate the server. Authentication takes place at the TLS layer through validation of the [ X.509 certificate chain](x509-client-certs.md). This is the same method used by your browser when you visit an HTTPS URL. If you want to use certificates from your own certificate authority, see [Manage your CA certificates](manage-your-CA-certs.md).

When your devices or other clients establish a TLS connection to an AWS IoT Core endpoint, AWS IoT Core presents a certificate chain that the devices use to verify that they're communicating with AWS IoT Core and not another server impersonating AWS IoT Core. The chain that is presented depends on a combination of the type of endpoint the device is connecting to and the [cipher suite](transport-security.md) that the client and AWS IoT Core negotiated during the TLS handshake.

## Endpoint types
<a name="endpoint-types"></a>

AWS IoT Core supports `iot:Data-ATS`. `iot:Data-ATS` endpoints present a server certificate signed by an [Amazon Trust Services](https://www.amazontrust.com/repository/) CA.

Certificates presented by ATS endpoints are cross signed by Starfield. Some TLS client implementations require validation of the root of trust and require that the Starfield CA certificates are installed in the client's trust stores.

**Warning**  
Using a method of certificate pinning that hashes the whole certificate (including the issuer name, and so on) is not recommended because this will cause certificate verification to fail because the ATS certificates we provide are cross signed by Starfield and have a different issuer name.

**Important**  
Use `iot:Data-ATS` endpoints. Symantec and Verisign certificates have been deprecated and are no longer supported by AWS IoT Core.

You can use the `describe-endpoint` command to create your ATS endpoint.

```
aws iot describe-endpoint --endpoint-type iot:Data-ATS
```

The `describe-endpoint` command returns an endpoint in the following format.

```
account-specific-prefix.iot.your-region.amazonaws.com
```

**Note**  
The first time `describe-endpoint` is called, an endpoint is created. All subsequent calls to `describe-endpoint` return the same endpoint.

**Note**  
To see your `iot:Data-ATS` endpoint in the AWS IoT Core console, choose **Settings**. The console displays only the `iot:Data-ATS` endpoint.

### Creating an `IotDataPlaneClient` with the AWS SDK for Java
<a name="java-client"></a>

To create an `IotDataPlaneClient` that uses an `iot:Data-ATS` endpoint, you must do the following. 
+ Create an `iot:Data-ATS` endpoint by using the [DescribeEndpoint](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEndpoint.html) API.
+ Specify that endpoint when you create the `IotDataPlaneClient`.

The following example performs both of these operations.

```
public void setup() throws Exception {
        IotClient client = IotClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_EAST_1).build();
        String endpoint = client.describeEndpoint(r -> r.endpointType("iot:Data-ATS")).endpointAddress();
        iot = IotDataPlaneClient.builder()
                                .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
                                .endpointOverride(URI.create("https://" + endpoint))
                                .region(Region.US_EAST_1)
                                .build();
}
```

## CA certificates for server authentication
<a name="server-authentication-certs"></a>

Depending on which type of data endpoint you are using and which cipher suite you have negotiated, AWS IoT Core server authentication certificates are signed by one of the following root CA certificates:

**Amazon Trust Services Endpoints (preferred)**

**Note**  
You might need to right click these links and select **Save link as...** to save these certificates as files.
+ RSA 2048 bit key: [https://www.amazontrust.com/repository/AmazonRootCA1.pem](https://www.amazontrust.com/repository/AmazonRootCA1.pem).
+ RSA 4096 bit key: Amazon Root CA 2. Reserved for future use.
+ ECC 256 bit key: [https://www.amazontrust.com/repository/AmazonRootCA3.pem](https://www.amazontrust.com/repository/AmazonRootCA3.pem).
+ ECC 384 bit key: Amazon Root CA 4. Reserved for future use.

These certificates are all cross-signed by the [ Starfield Root CA Certificate](https://www.amazontrust.com/repository/SFSRootCAG2.pem). All new AWS IoT Core regions, beginning with the May 9, 2018 launch of AWS IoT Core in the Asia Pacific (Mumbai) Region, serve only ATS certificates.

**VeriSign Endpoints (legacy)**
+ RSA 2048 bit key: [VeriSign Class 3 Public Primary G5 root CA certificate](https://www.digicert.com/kb/digicert-root-certificates.htm)

## Server authentication guidelines
<a name="server-authentication-guidelines"></a>

There are many variables that can affect a device's ability to validate the AWS IoT Core server authentication certificate. For example, devices may be too memory constrained to hold all possible root CA certificates, or devices may implement a non-standard method of certificate validation. For these reasons we suggest following these guidelines:
+ We recommend that you use your ATS endpoint and install all supported Amazon Root CA certificates.
+ If you cannot store all of these certificates on your device and if your devices do not use ECC-based validation, you can omit the [https://www.amazontrust.com/repository/AmazonRootCA3.pem](https://www.amazontrust.com/repository/AmazonRootCA3.pem) and [https://www.amazontrust.com/repository/AmazonRootCA4.pem](https://www.amazontrust.com/repository/AmazonRootCA4.pem) ECC certificates. If your devices do not implement RSA-based certificate validation, you can omit the [https://www.amazontrust.com/repository/AmazonRootCA1.pem](https://www.amazontrust.com/repository/AmazonRootCA1.pem) and [https://www.amazontrust.com/repository/AmazonRootCA2.pem](https://www.amazontrust.com/repository/AmazonRootCA2.pem) RSA certificates. You might need to right click these links and select **Save link as...** to save these certificates as files.
+ If you are experiencing server certificate validation issues when connecting to your ATS endpoint, try adding the relevant cross-signed Amazon Root CA certificate to your trust store. You might need to right click these links and select **Save link as...** to save these certificates as files.
  + [Cross-signed Amazon Root CA 1](https://www.amazontrust.com/repository/G2-RootCA1.pem)
  + [Cross-signed Amazon Root CA 2](https://www.amazontrust.com/repository/G2-RootCA2.pem) - Reserved for future use.
  + [Cross-signed Amazon Root CA 3](https://www.amazontrust.com/repository/G2-RootCA3.pem)
  + [Cross-signed Amazon Root CA 4 - Reserved for future use.](https://www.amazontrust.com/repository/G2-RootCA4.pem)
+ If you are experiencing server certificate validation issues, your device may need to explicitly trust the root CA. Try adding the [https://www.amazontrust.com/repository/SFSRootCAG2.pem](https://www.amazontrust.com/repository/SFSRootCAG2.pem) to your trust store.
+ If you still experience issues after executing the steps above, please contact [AWS Developer Support](https://aws.amazon.com/premiumsupport/plans/developers/). 

**Note**  
CA certificates have an expiration date after which they cannot be used to validate a server's certificate. CA certificates might have to be replaced before their expiration date. Make sure that you can update the root CA certificates on all of your devices or clients to help ensure ongoing connectivity and to keep up to date with security best practices.

**Note**  
When connecting to AWS IoT Core in your device code, pass the certificate into the API you are using to connect. The API you use will vary by SDK. For more information, see the [AWS IoT Core Device SDKs](iot-sdks.md).

# Client authentication
<a name="client-authentication"></a>

AWS IoT supports three types of identity principals for device or client authentication:
+ [X.509 client certificates](x509-client-certs.md)
+ [IAM users, groups, and roles](iam-users-groups-roles.md)
+ [Amazon Cognito identities](cognito-identities.md)

These identities can be used with devices, mobile, web, or desktop applications. They can even be used by a user typing AWS IoT command line interface (CLI) commands. Typically, AWS IoT devices use X.509 certificates, while mobile applications use Amazon Cognito identities. Web and desktop applications use IAM or federated identities. AWS CLI commands use IAM. For more information about IAM identities, see [Identity and access management for AWS IoT](security-iam.md).

# X.509 client certificates
<a name="x509-client-certs"></a>

X.509 certificates provide AWS IoT with the ability to authenticate client and device connections. Client certificates must be registered with AWS IoT before a client can communicate with AWS IoT. A client certificate can be registered in multiple AWS accounts in the same AWS Region to facilitate moving devices between your AWS accounts in the same region. See [Using X.509 client certificates in multiple AWS accounts with multi-account registration](#multiple-account-cert) for more information. 

We recommend that each device or client be given a unique certificate to enable fine-grained client management actions, including certificate revocation. Devices and clients must also support rotation and replacement of certificates to help ensure smooth operation as certificates expire.

For information about using X.509 certificates to support more than a few devices, see [Device provisioning](iot-provision.md) to review the different certificate management and provisioning options that AWS IoT supports.

**AWS IoT supports these types of X.509 client certificates:**
+  X.509 certificates generated by AWS IoT
+  X.509 certificates signed by a CA registered with AWS IoT.
+  X.509 certificates signed by a CA that is not registered with AWS IoT.

This section describes how to manage X.509 certificates in AWS IoT. You can use the AWS IoT console or AWS CLI to perform these certificate operations:
+ [Create AWS IoT client certificates](device-certs-create.md)
+ [Create your own client certificates](device-certs-your-own.md)
+ [Register a client certificate](register-device-cert.md)
+ [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md)
+ [Revoke a client certificate](revoke-ca-cert.md)

For more information about the AWS CLI commands that perform these operations, see [AWS IoT CLI Reference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/index.html).

## Using X.509 client certificates
<a name="x509-client-cert-basics"></a>

X.509 certificates authenticate client and device connections to AWS IoT. X.509 certificates provide several benefits over other identification and authentication mechanisms. X.509 certificates enable asymmetric keys to be used with devices. For example, you could burn private keys into secure storage on a device so that sensitive cryptographic material never leaves the device. X.509 certificates provide stronger client authentication over other schemes, such as user name and password or bearer tokens, because the private key never leaves the device.

AWS IoT authenticates client certificates using the TLS protocol's client authentication mode. TLS support is available in many programming languages and operating systems and is commonly used for encrypting data. In TLS client authentication, AWS IoT requests an X.509 client certificate and validates the certificate's status and AWS account against a registry of certificates. It then challenges the client for proof of ownership of the private key that corresponds to the public key contained in the certificate. AWS IoT requires clients to send the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol. For more information on configuring the SNI extension, see [Transport security in AWS IoT Core](transport-security.md).

To facilitate a secure and consistent client connection to AWS IoT core, a X.509 client certificate must possess the following:
+ Registered in AWS IoT Core. For more information, see [Register a client certificate](register-device-cert.md).
+ Have a status state of `ACTIVE`. For more information, see [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md).
+ Not yet reached the certificate expiration date.

You can create client certificates that use the Amazon Root CA and you can use your own client certificates signed by another certificate authority (CA). For more information about using the AWS IoT console to create certificates that use the Amazon Root CA, see [Create AWS IoT client certificates](device-certs-create.md). For more information about using your own X.509 certificates, see [Create your own client certificates](device-certs-your-own.md).

The date and time when certificates signed by a CA certificate expire are set when the certificate is created. X.509 certificates generated by AWS IoT expire at midnight UTC on December 31, 2049 (2049-12-31T23:59:59Z).

AWS IoT Device Defender can perform audits on your AWS account and devices supporting common IoT security best practices. This includes managing the expiration dates of X.509 certificates signed by your CA or the Amazon Root CA. For more information on managing a certificate's expiration date, see [Device certificate expiring](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/audit-chk-device-cert-approaching-expiration.html) and [CA certificate expiring](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/audit-chk-ca-cert-approaching-expiration.html).

On the official AWS IoT blog, a deeper dive into the management of device certificate rotation and security best practices is explored in [How to manage IoT device certificate rotation using AWS IoT](https://aws.amazon.com/blogs/iot/how-to-manage-iot-device-certificate-rotation-using-aws-iot/).

## Using X.509 client certificates in multiple AWS accounts with multi-account registration
<a name="multiple-account-cert"></a>

Multi-account registration makes it possible to move devices between your AWS accounts in the same Region or in different Regions. You can register, test, and configure a device in a pre-production account, and then register and use the same device and device certificate in a production account. You can also register the client certificate on the device or the device certificates without a CA that is registered with AWS IoT. For more information, see [Register a client certificate signed by an unregistered CA (CLI).](manual-cert-registration.md#manual-cert-registration-noca-cli)

**Note**  
Certificates used for multi-account registration are supported on the `iot:Data-ATS`, `iot:Data` (legacy), `iot:Jobs`, and `iot:CredentialProvider` endpoint types. For more information about AWS IoT device endpoints, see [AWS IoT device data and service endpoints](iot-connect-devices.md#iot-connect-device-endpoints).

Devices that use multi-account registration must send the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field, when they connect to AWS IoT. AWS IoT uses the endpoint address in `host_name` to route the connection to the correct AWS IoT account. Existing devices that don't send a valid endpoint address in `host_name` will continue to work, but they will not be able to use the features that require this information. For more information about the SNI extension and to learn how to identify the endpoint address for the `host_name` field, see [Transport security in AWS IoT Core](transport-security.md). 

**To use multi-account registration**

1. You can register the device certificates with a CA. You can register the signing CA in multiple accounts in `SNI_ONLY` mode and use that CA to register the same client certificate to multiple accounts. For more information, see [Register a CA certificate in SNI\$1ONLY mode (CLI) - Recommended](manage-your-CA-certs.md#register-CA-cert-SNI-cli).

1. You can register the device certificates without a CA. See [Register a client certificate signed by an unregistered CA (CLI)](manual-cert-registration.md#manual-cert-registration-noca-cli). Registering a CA is optional. You're not required to register the CA that signed the device certificates with AWS IoT.

## Certificate signing algorithms supported by AWS IoT
<a name="x509-cert-algorithms"></a>

AWS IoT supports the following certificate-signing algorithms:
+ SHA256WITHRSA
+ SHA384WITHRSA
+ SHA512WITHRSA
+ SHA256WITHRSAANDMGF1 (RSASSA-PSS)
+ SHA384WITHRSAANDMGF1 (RSASSA-PSS)
+ SHA512WITHRSAANDMGF1 (RSASSA-PSS)
+ DSA\$1WITH\$1SHA256
+ ECDSA-WITH-SHA256
+ ECDSA-WITH-SHA384
+ ECDSA-WITH-SHA512

For more information about certificate authentication and security, see [Device certificate key quality](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/audit-chk-device-cert-key-quality.html).

**Note**  
The certificate signing request (CSR) must include a public key. The key can be either an RSA key with a length of at least 2,048 bits or an ECC key from NIST P-256, NIST P-384, or NIST P-521 curves. For more information, see [CreateCertificateFromCsr](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateCertificateFromCsr.html) in the *AWS IoT API Reference Guide*.

## Key algorithms supported by AWS IoT
<a name="x509-cert-key-algorithms"></a>

The table below shows how key algorithms are supported:


****  

| Key algorithm | Certificate signing algorithm | TLS version | Supported? Yes or No | 
| --- | --- | --- | --- | 
| RSA with a key size of at least 2048 bits | All | TLS 1.2 TLS 1.3 | Yes | 
| ECC NIST P-256/P-384/P-521 | All | TLS 1.2 TLS 1.3 | Yes | 
| RSA-PSS with a key size of at least 2048 bits | All | TLS 1.2 | No | 
| RSA-PSS with a key size of at least 2048 bits | All | TLS 1.3 | Yes | 

To create a certificate using [CreateCertificateFromCSR](https://docs.aws.amazon.com//iot/latest/apireference/API_CreateCertificateFromCsr.html), you can use a supported key algorithm to generate a public key for your CSR. To register your own certificate using [RegisterCertificate](https://docs.aws.amazon.com//iot/latest/apireference/API_RegisterCertificate.html) or [RegisterCertificateWithoutCA](https://docs.aws.amazon.com//iot/latest/apireference/API_RegisterCertificateWithoutCA.html), you can use a supported key algorithm to generate a public key for the certificate.

For more information, see [Security policies](https://docs.aws.amazon.com//iot/latest/developerguide/transport-security.html#tls-policy-table).

# Create AWS IoT client certificates
<a name="device-certs-create"></a>

AWS IoT provides client certificates that are signed by the Amazon Root certificate authority (CA).

This topic describes how to create a client certificate signed by the Amazon Root certificate authority and download the certificate files. After you create the client certificate files, you must install them on the client.

**Note**  
Each X.509 client certificate provided by AWS IoT holds issuer and subject attributes that you set at the time of certificate creation. The certificate attributes are immutable only after the certificate is created.

You can use the AWS IoT console or the AWS CLI to create an AWS IoT certificate signed by the Amazon Root certificate authority.

## Create an AWS IoT certificate (console)
<a name="device-certs-create-console"></a>

**To create an AWS IoT certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the navigation pane, choose **Security**, then choose **Certificates**, and then choose **Create**.

1. Choose **One-click certificate creation (recommended)** - **Create certificate**.

1. From the **Certificate created** page, download the client certificate files for the thing, public key, and private key to a secure location. These certificates generated by AWS IoT are only available for use with AWS IoT services.

   If you also need the Amazon Root CA certificate file, this page also has the link to the page where you can download it.

1. A client certificate has now been created and registered with AWS IoT. You must activate the certificate before you use it in a client.

    To activate the client certificate now, choose **Activate**. If you don't want to activate the certificate now, see [Activate a client certificate (console)](activate-or-deactivate-device-cert.md#activate-device-cert-console) to learn how to activate the certificate later.

   

1. If you want to attach a policy to the certificate, choose **Attach a policy**.

   If you don't want to attach a policy now, choose **Done** to finish. You can attach a policy later.

After you complete the procedure, install the certificate files on the client.

## Create an AWS IoT certificate (CLI)
<a name="device-certs-create-cli"></a>

The AWS CLI provides the **[create-keys-and-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-keys-and-certificate.html)** command to create client certificates signed by the Amazon Root certificate authority. This command, however, does not download the Amazon Root CA certificate file. You can download the Amazon Root CA certificate file from [CA certificates for server authentication](server-authentication.md#server-authentication-certs). 

This command creates private key, public key, and X.509 certificate files and registers and activates the certificate with AWS IoT.

```
aws iot create-keys-and-certificate \
    --set-as-active \
    --certificate-pem-outfile certificate_filename.pem \
    --public-key-outfile public_filename.key \
    --private-key-outfile private_filename.key
```

If you don't want to activate the certificate when you create and register it, this command creates private key, public key, and X.509 certificate files and registers the certificate, but it does not activate it. [Activate a client certificate (CLI)](activate-or-deactivate-device-cert.md#activate-device-cert-cli) describes how to activate the certificate later.

```
aws iot create-keys-and-certificate \
    --no-set-as-active \
    --certificate-pem-outfile certificate_filename.pem \
    --public-key-outfile public_filename.key \
    --private-key-outfile private_filename.key
```



Install the certificate files on the client.

# Create your own client certificates
<a name="device-certs-your-own"></a>

AWS IoT supports client certificates signed by any root or intermediate certificate authorities (CA). AWS IoT uses CA certificates to verify the ownership of certificates. To use device certificates signed by a CA that’s not Amazon’s CA, the CA’s certificate must be registered with AWS IoT so that we can verify the device certificate’s ownership.

AWS IoT supports multiple ways for bringing your own certificates (BYOC): 
+ First, register the CA that’s used for signing the client certificates and then register individual client certificates. If you want to register the device or client to its client certificate when it first connects to AWS IoT (also known as [Just-in-Time Provisioning](https://docs.aws.amazon.com//iot/latest/developerguide/jit-provisioning.html)), you must register the signing CA with AWS IoT and activate auto-registration.
+ If you can’t register the signing CA, you can choose to register client certificates without CA. For devices registered without CA, you’ll need to present [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) when you connect them to AWS IoT.

**Note**  
To register client certificates using CA, you must register the signing CA with AWS IoT, not any other CAs in the hierarchy.

**Note**  
A CA certificate can be registered in `DEFAULT` mode by only one account in a Region. A CA certificate can be registered in `SNI_ONLY` mode by multiple accounts in a Region. 

For more information about using X.509 certificates to support more than a few devices, see [Device provisioning](iot-provision.md) to review the different certificate management and provisioning options that AWS IoT supports.

**Topics**
+ [Manage your CA certificates](manage-your-CA-certs.md)
+ [Create a client certificate using your CA certificate](create-device-cert.md)

# Manage your CA certificates
<a name="manage-your-CA-certs"></a>

This section describes common tasks for managing your own certificate authority (CA) certificates.

You can register your certificate authority (CA) with AWS IoT if you are using client certificates signed by a CA that AWS IoT doesn't recognize.

If you want clients to automatically register their client certificates with AWS IoT when they first connect, the CA that signed the client certificates must be registered with AWS IoT. Otherwise, you don't need to register the CA certificate that signed the client certificates.

**Note**  
A CA certificate can be registered in `DEFAULT` mode by only one account in a Region. A CA certificate can be registered in `SNI_ONLY` mode by multiple accounts in a Region.

**Topics**
+ [Create a CA certificate](#create-your-CA-cert)
+ [Register your CA certificate](#register-CA-cert)
+ [Deactivate a CA certificate](#deactivate-ca-cert)

## Create a CA certificate
<a name="create-your-CA-cert"></a>

If you do not have a CA certificate, you can use [OpenSSL v1.1.1i](https://www.openssl.org/) tools to create one.

**Note**  
You can't perform this procedure in the AWS IoT console.

**To create a CA certificate using [OpenSSL v1.1.1i](https://www.openssl.org/) tools**

1. Generate a key pair.

   ```
   openssl genrsa -out root_CA_key_filename.key 2048
   ```

1. Use the private key from the key pair to generate a CA certificate.

   ```
   openssl req -x509 -new -nodes \
       -key root_CA_key_filename.key \
       -sha256 -days 1024 \
       -out root_CA_cert_filename.pem
   ```

## Register your CA certificate
<a name="register-CA-cert"></a>

These procedures describe how to register a certificate from a certificate authority (CA) that's not Amazon's CA. AWS IoT Core uses CA certificates to verify the ownership of certificates. To use device certificates signed by a CA that's not Amazon's CA, you must register the CA certificate with AWS IoT Core so that it can verify the device certificate's ownership.

### Register a CA certificate (console)
<a name="register-CA-cert-console"></a>

**Note**  
To register a CA certificate in the console, start in the console at [Register CA certificate](https://console.aws.amazon.com//iot/home#/create/cacertificate). You can register your CA in Multi-account mode and without the need to provide a verification certificate or access to the private key. A CA can be registered in Multi-account mode by multiple AWS accounts in the same AWS Region. You can register your CA in Single-account mode by providing a verification certificate and proof of ownership of CA’s private key.

### Register a CA certificate (CLI)
<a name="register-CA-cert-cli"></a>

You can register a CA certificate in `DEFAULT` mode or `SNI_ONLY` mode. A CA can be registered in `DEFAULT` mode by one AWS account in one AWS Region. A CA can be registered in `SNI_ONLY` mode by multiple AWS accounts in the same AWS Region. For more information about CA certificate mode, see [certificateMode](https://docs.aws.amazon.com//iot/latest/apireference/API_CACertificateDescription.html#iot-Type-CACertificateDescription-certificateMode).

**Note**  
We recommend that you register a CA in `SNI_ONLY` mode. You don't need to provide a verification certificate or access to the private key, and you can register the CA by multiple AWS accounts in the same AWS Region.

#### Register a CA certificate in SNI\$1ONLY mode (CLI) - Recommended
<a name="register-CA-cert-SNI-cli"></a>

**Prerequisites**

Make sure you have the following available on your computer before you continue:
+ The root CA's certificate file (referenced in the following example as `root_CA_cert_filename.pem`)
+ [OpenSSL v1.1.1i](https://www.openssl.org/) or later

**To register a CA certificate in `SNI_ONLY` mode using the AWS CLI**

1. Register the CA certificate with AWS IoT. Using the **register-ca-certificate** command, enter the CA certificate file name. For more information, see [register-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot register-ca-certificate \
       --ca-certificate file://root_CA_cert_filename.pem \
       --certificate-mode SNI_ONLY
   ```

   If successful, this command returns the *certificateId*.

1. At this point, the CA certificate has been registered with AWS IoT but is inactive. The CA certificate must be active before you can register any client certificates that it has signed.

   This step activates the CA certificate.

   To activate the CA certificate, use the **update-certificate** command as follows. For more information, see [update-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot update-ca-certificate \
       --certificate-id certificateId \
       --new-status ACTIVE
   ```

To see the status of the CA certificate, use the **describe-ca-certificate** command. For more information, see [describe-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) in the *AWS CLI Command Reference*.

#### Register a CA certificate in `DEFAULT` mode (CLI)
<a name="register-CA-cert-default-cli"></a>

**Prerequisites**

Make sure you have the following available on your computer before you continue:
+ The root CA's certificate file (referenced in the following example as `root_CA_cert_filename.pem`)
+ The root CA certificate's private key file (referenced in the following example as `root_CA_key_filename.key`)
+ [OpenSSL v1.1.1i](https://www.openssl.org/) or later

**To register a CA certificate in `DEFAULT` mode using the AWS CLI**

1. To get a registration code from AWS IoT, use **get-registration-code**. Save the returned `registrationCode` to use as the `Common Name` of the private key verification certificate. For more information, see [get-registration-code](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-registration-code.html) in the *AWS CLI Command Reference*.

   ```
   aws iot get-registration-code
   ```

1. Generate a key pair for the private key verification certificate:

   ```
   openssl genrsa -out verification_cert_key_filename.key 2048
   ```

1. Create a certificate signing request (CSR) for the private key verification certificate. Set the `Common Name` field of the certificate to the `registrationCode` returned by **get-registration-code**.

   ```
   openssl req -new \
       -key verification_cert_key_filename.key \
       -out verification_cert_csr_filename.csr
   ```

   You are prompted for some information, including the `Common Name` for the certificate.

   ```
   You are about to be asked to enter information that will be incorporated
   into your certificate request.
   What you are about to enter is what is called a Distinguished Name or a DN.
   There are quite a few fields but you can leave some blank
   For some fields there will be a default value,
   If you enter '.', the field will be left blank.
   -----
   Country Name (2 letter code) [AU]:
       State or Province Name (full name) []:
       Locality Name (for example, city) []:
       Organization Name (for example, company) []:
       Organizational Unit Name (for example, section) []:
       Common Name (e.g. server FQDN or YOUR name) []:your_registration_code
       Email Address []:
   
       Please enter the following 'extra' attributes
       to be sent with your certificate request
       A challenge password []:
       An optional company name []:
   ```

1. Use the CSR to create a private key verification certificate:

   ```
   openssl x509 -req \
       -in verification_cert_csr_filename.csr \
       -CA root_CA_cert_filename.pem \
       -CAkey root_CA_key_filename.key \
       -CAcreateserial \
       -out verification_cert_filename.pem \
       -days 500 -sha256
   ```

1. Register the CA certificate with AWS IoT. Pass in the CA certificate file name and the private key verification certificate file name to the **register-ca-certificate** command, as follows. For more information, see [register-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot register-ca-certificate \
       --ca-certificate file://root_CA_cert_filename.pem \
       --verification-cert file://verification_cert_filename.pem
   ```

   This command returns the *certificateId*, if successful.

1. At this point, the CA certificate has been registered with AWS IoT but is not active. The CA certificate must be active before you can register any client certificates it has signed.

   This step activates the CA certificate.

   To activate the CA certificate, use the **update-certificate** command as follows. For more information, see [update-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) in the *AWS CLI Command Reference*.

   ```
   aws iot update-ca-certificate \
       --certificate-id certificateId \
       --new-status ACTIVE
   ```

To see the status of the CA certificate, use the **describe-ca-certificate** command. For more information, see [describe-ca-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) in the *AWS CLI Command Reference*.

### Create a CA verification certificate to register the CA certificate in the console
<a name="create-CA-verification-cert"></a>

**Note**  
This procedure is only for use if you are registering a CA certificate from the AWS IoT console.  
If you did not come to this procedure from the AWS IoT console, start the CA certificate registration process in the console at [Register CA certificate](https://console.aws.amazon.com//iot/home#/create/cacertificate). 

Make sure you have the following available on the same computer before you continue:
+ The root CA's certificate file (referenced in the following example as `root_CA_cert_filename.pem`)
+ The root CA certificate's private key file (referenced in the following example as `root_CA_key_filename.key`)
+ [OpenSSL v1.1.1i](https://www.openssl.org/) or later

**To use the command line interface to create a CA verification certificate to register your CA certificate in the console**

1. Replace `verification_cert_key_filename.key` with the name of the verification certificate key file that you want to create (for example, **verification\$1cert.key**). Then run this command to generate a key pair for the private key verification certificate:

   ```
   openssl genrsa -out verification_cert_key_filename.key 2048
   ```

1. Replace `verification_cert_key_filename.key` with the name of the key file that you created in step 1.

   Replace `verification_cert_csr_filename.csr` with the name of the certificate signing request (CSR) file that you want to create. For example, **verification\$1cert.csr**.

   Run this command to create the CSR file.

   ```
   openssl req -new \
       -key verification_cert_key_filename.key \
       -out verification_cert_csr_filename.csr
   ```

   The command prompts you for additional information that's explained later.

1. In the AWS IoT console, in the **Verification certificate** container, copy the registration code.

1. The information that the **openssl** command prompts you for is shown in the following example. Except for the `Common Name` field, you can enter your own values or keep them blank.

   In the `Common Name` field, paste the registration code that you copied in the previous step.

   ```
   You are about to be asked to enter information that will be incorporated
   into your certificate request.
   What you are about to enter is what is called a Distinguished Name or a DN.
   There are quite a few fields but you can leave some blank
   For some fields there will be a default value,
   If you enter '.', the field will be left blank.
   -----
   Country Name (2 letter code) [AU]:
       State or Province Name (full name) []:
       Locality Name (for example, city) []:
       Organization Name (for example, company) []:
       Organizational Unit Name (for example, section) []:
       Common Name (e.g. server FQDN or YOUR name) []:your_registration_code
       Email Address []:
   
       Please enter the following 'extra' attributes
       to be sent with your certificate request
       A challenge password []:
       An optional company name []:
   ```

   After you finish, the command creates the CSR file.

1. Replace `verification_cert_csr_filename.csr` with the `verification_cert_csr_filename.csr` you used in the previous step.

   Replace `root_CA_cert_filename.pem` with the file name of the CA certificate that you want to register.

   Replace `root_CA_key_filename.key` with the file name of the CA certificate's private key file.

   Replace `verification_cert_filename.pem` with the file name of the verification certificate that you want to create. For example, **verification\$1cert.pem**.

   ```
   openssl x509 -req \
       -in verification_cert_csr_filename.csr \
       -CA root_CA_cert_filename.pem \
       -CAkey root_CA_key_filename.key \
       -CAcreateserial \
       -out verification_cert_filename.pem \
       -days 500 -sha256
   ```

1. After the OpenSSL command completes, you should have these files ready to use for when you return to the console.
   + Your CA certificate file (`root_CA_cert_filename.pem` used in the previous command)
   + The verification certificate that you created in the previous step (*verification\$1cert\$1filename.pem* used in the previous command)

## Deactivate a CA certificate
<a name="deactivate-ca-cert"></a>

When a certificate authority (CA) certificate is enabled for automatic client certificate registration, AWS IoT checks the CA certificate to make sure the CA is `ACTIVE`. If the CA certificate is `INACTIVE`, AWS IoT doesn't allow the client certificate to be registered.

By setting the CA certificate to `INACTIVE`, you prevent any new client certificates issued by the CA from being registered automatically.

**Note**  
Any registered client certificates that were signed by the compromised CA certificate continue to work until you explicitly revoke each one of them.

### Deactivate a CA certificate (console)
<a name="deactivate-ca-cert-console"></a>

**To deactivate a CA certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **CAs**.

1. In the list of certificate authorities, find the one that you want to deactivate, and choose the ellipsis icon to open the option menu.

1. On the option menu, choose **Deactivate**.

The certificate authority should show as **Inactive** in the list.

**Note**  
The AWS IoT console does not provide a way to list the certificates that were signed by the CA you deactivated. For an AWS CLI option to list those certificates, see [Deactivate a CA certificate (CLI)](#deactivate-ca-cert-cli).

### Deactivate a CA certificate (CLI)
<a name="deactivate-ca-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html) command to deactivate a CA certificate.

```
aws iot update-ca-certificate \
    --certificate-id certificateId \
    --new-status INACTIVE
```

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-certificates-by-ca.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-certificates-by-ca.html) command to get a list of all registered client certificates that were signed by the specified CA. For each client certificate signed by the specified CA certificate, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to revoke the client certificate to prevent it from being used.

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) command to see the status of the CA certificate.

# Create a client certificate using your CA certificate
<a name="create-device-cert"></a>

You can use your own certificate authority (CA) to create client certificates. The client certificate must be registered with AWS IoT before use. For information about the registration options for your client certificates, see [Register a client certificate](register-device-cert.md).

## Create a client certificate (CLI)
<a name="create-device-cert-cli"></a>

**Note**  
You can't perform this procedure in the AWS IoT console.

**To create a client certificate using the AWS CLI**

1. Generate a key pair.

   ```
   openssl genrsa -out device_cert_key_filename.key 2048
   ```

1. Create a CSR for the client certificate.

   ```
   openssl req -new \
       -key device_cert_key_filename.key \
       -out device_cert_csr_filename.csr
   ```

   You are prompted for some information, as shown here:

   ```
   You are about to be asked to enter information that will be incorporated
   into your certificate request.
   What you are about to enter is what is called a Distinguished Name or a DN.
   There are quite a few fields but you can leave some blank
   For some fields there will be a default value,
   If you enter '.', the field will be left blank.
   -----
   Country Name (2 letter code) [AU]:
       State or Province Name (full name) []:
       Locality Name (for example, city) []:
       Organization Name (for example, company) []:
       Organizational Unit Name (for example, section) []:
       Common Name (e.g. server FQDN or YOUR name) []:
       Email Address []:
   
       Please enter the following 'extra' attributes
       to be sent with your certificate request
       A challenge password []:
       An optional company name []:
   ```

1. Create a client certificate from the CSR.

   ```
   openssl x509 -req \
       -in device_cert_csr_filename.csr \
       -CA root_CA_cert_filename.pem \
       -CAkey root_CA_key_filename.key \
       -CAcreateserial \
       -out device_cert_filename.pem \
       -days 500 -sha256
   ```

 At this point, the client certificate has been created, but it has not yet been registered with AWS IoT. For information about how and when to register the client certificate, see [Register a client certificate](register-device-cert.md). 

# Register a client certificate
<a name="register-device-cert"></a>

Client certificates must be registered with AWS IoT to enable communications between the client and AWS IoT. You can register each client certificate manually, or you can configure the client certificates to register automatically when the client connects to AWS IoT for the first time.

 If you want your clients and devices to register their client certificates when they first connect, you must [Register your CA certificate](manage-your-CA-certs.md#register-CA-cert) used to sign the client certificate with AWS IoT in the Regions in which you want to use it. The Amazon Root CA is automatically registered with AWS IoT. 

Client certificates can be shared by AWS accounts and Regions. The procedures in these topics must be performed in each account and Region in which you want to use the client certificate. The registration of a client certificate in one account or Region is not automatically recognized by another.

**Note**  
Clients that use the Transport Layer Security (TLS) protocol to connect to AWS IoT must support the [Server Name Indication (SNI) extension](https://tools.ietf.org/html/rfc3546#section-3.1) to TLS. For more information, see [Transport security in AWS IoT Core](transport-security.md).

**Topics**
+ [Register a client certificate manually](manual-cert-registration.md)
+ [Register a client certificate when the client connects to AWS IoT just-in-time registration (JITR)](auto-register-device-cert.md)

# Register a client certificate manually
<a name="manual-cert-registration"></a>

You can register a client certificate manually by using the AWS IoT console and AWS CLI.

The registration procedure to use depends on whether the certificate will be shared by AWS accounts and Regions. The registration of a client certificate in one account or Region is not automatically recognized by another.

The procedures in this topic must be performed in each account and Region in which you want to use the client certificate. Client certificates can be shared by AWS accounts and Regions. 

## Register a client certificate signed by a registered CA (console)
<a name="manual-cert-registration-console"></a>

**Note**  
Before you perform this procedure, make sure that you have the client certificate's .pem file and that the client certificate was signed by a CA that you have [registered with AWS IoT](manage-your-CA-certs.md#register-CA-cert).

**To register an existing certificate with AWS IoT using the console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the navigation pane, under the **Manage** section, choose **Security**, and then choose **Certificates**.

1. On the **Certificates** page in the **Certificates** dialog box, choose **Add certificate**, and then choose **Register certificates**.

1. On the **Register certificate** page in the **Certificates to upload** dialog box, do the following:
   + Choose **CA is registered with AWS IoT**.
   + From **Choose a CA certificate**, select your **Certification authority**. 
     + Choose **Register a new CA** to register a new **Certification authority** that's not registered with AWS IoT.
     + Leave **Choose a CA certificate** blank if **Amazon Root certificate authority** is your certification authority.
   + Select up to 10 certificates to upload and register with AWS IoT.
     + Use the certificate files you created in [Create AWS IoT client certificates](device-certs-create.md) and [Create a client certificate using your CA certificate](create-device-cert.md).
   + Choose **Activate** or **Deactivate**. If you choose **Deactive**, [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md) explains how to activate your certificate after certificate registration.
   + Choose **Register**.

On the **Certificates** page in the **Certificates** dialog box, your registered certificates will now appear.

## Register a client certificate signed by an unregistered CA (console)
<a name="manual-cert-registration-console-noca"></a>

**Note**  
Before you perform this procedure, make sure that you have the client certificate's .pem file.

**To register an existing certificate with AWS IoT using the console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**, and then choose **Create**.

1. On **Create a certificate**, locate the **Use my certificate** entry, and choose **Get started**.

1. On **Select a CA**, choose **Next**.

1.  On **Register existing device certificates**, choose **Select certificates**, and select up to 10 certificate files to register. 

1.  After closing the file dialog box, select whether you want to activate or revoke the client certificates when you register them.

   If you don't activate a certificate when it is registered, [Activate a client certificate (console)](activate-or-deactivate-device-cert.md#activate-device-cert-console) describes how to activate it later. 

   If a certificate is revoked when it is registered, it can't be activated later.

   After you choose the certificate files to register, and select the actions to take after registration, select **Register certificates**.

The client certificates that are registered successfully appear in the list of certificates.

## Register a client certificate signed by a registered CA (CLI)
<a name="manual-cert-registration-cli"></a>

**Note**  
Before you perform this procedure, make sure that you have the certificate authority (CA) .pem and the client certificate's .pem file. The client certificate must be signed by a certificate authority (CA) that you have [registered with AWS IoT](manage-your-CA-certs.md#register-CA-cert).

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate.html) command to register, but not activate, a client certificate.

```
aws iot register-certificate \
    --certificate-pem file://device_cert_filename.pem \
    --ca-certificate-pem file://ca_cert_filename.pem
```

The client certificate is registered with AWS IoT, but it is not active yet. See [Activate a client certificate (CLI)](activate-or-deactivate-device-cert.md#activate-device-cert-cli) for information on how to activate it later.

You can also activate the client certificate when you register it by using this command.

```
aws iot register-certificate \
    --set-as-active \
    --certificate-pem file://device_cert_filename.pem \
    --ca-certificate-pem file://ca_cert_filename.pem
```

For more information about activating the certificate so that it can be used to connect to AWS IoT, see [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md)

## Register a client certificate signed by an unregistered CA (CLI)
<a name="manual-cert-registration-noca-cli"></a>

**Note**  
Before you perform this procedure, make sure that you have the certificate's .pem file.

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate-without-ca.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate-without-ca.html) command to register, but not activate, a client certificate.

```
aws iot register-certificate-without-ca \
    --certificate-pem file://device_cert_filename.pem
```

The client certificate is registered with AWS IoT, but it is not active yet. See [Activate a client certificate (CLI)](activate-or-deactivate-device-cert.md#activate-device-cert-cli) for information on how to activate it later.

You can also activate the client certificate when you register it by using this command.

```
aws iot register-certificate-without-ca \
    --status ACTIVE \
    --certificate-pem file://device_cert_filename.pem
```

For more information about activating the certificate so that it can be used to connect to AWS IoT, see [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md).

# Register a client certificate when the client connects to AWS IoT just-in-time registration (JITR)
<a name="auto-register-device-cert"></a>

You can configure a CA certificate to enable client certificates it has signed to register with AWS IoT automatically the first time the client connects to AWS IoT.

To register client certificates when a client connects to AWS IoT for the first time, you must enable the CA certificate for automatic registration and configure the first connection by the client to provide the required certificates.

## Configure a CA certificate to support automatic registration (console)
<a name="enable-auto-registration-console"></a>

**To configure a CA certificate to support automatic client certificate registration using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **CAs**.

1. In the list of certificate authorities, find the one for which you want to enable automatic registration, and open the option menu by using the ellipsis icon.

1. On the option menu, choose **Enable auto-registration**.

**Note**  
The auto-registration status is not shown in the list of certificate authorities. To see the auto-registration status of a certificate authority, you must open the **Details** page of the certificate authority.

## Configure a CA certificate to support automatic registration (CLI)
<a name="enable-auto-registration-cli"></a>

If you have already registered your CA certificate with AWS IoT, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html) command to set `autoRegistrationStatus` of the CA certificate to `ENABLE`.

```
aws iot update-ca-certificate \
--certificate-id caCertificateId \
--new-auto-registration-status ENABLE
```

If you want to enable `autoRegistrationStatus` when you register the CA certificate, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html) command.

```
aws iot register-ca-certificate \
--allow-auto-registration  \
--ca-certificate file://root_CA_cert_filename.pem \
--verification-cert file://verification_cert_filename.pem
```

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html) command to see the status of the CA certificate.

## Configure the first connection by a client for automatic registration
<a name="configure-auto-reg-first-connect"></a>

When a client attempts to connect to AWS IoT for the first time, the client certificate signed by your CA certificate must be present on the client during the Transport Layer Security (TLS) handshake.

When the client connects to AWS IoT, use the client certificate you created in [Create AWS IoT client certificates](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-create.html) or [Create your own client certificates](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html). AWS IoT recognizes the CA certificate as a registered CA certificate, registers the client certificate, and sets its status to `PENDING_ACTIVATION`. This means that the client certificate was automatically registered and is awaiting activation. The client certificate's state must be `ACTIVE` before it can be used to connect to AWS IoT. See [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md) for information on activating a client certificate.

**Note**  
You can provision devices using AWS IoT Core just-in-time registration (JITR) feature without having to send the entire trust chain on devices' first connection to AWS IoT Core. Presenting the CA certificate is optional but the device is required to send the [Server Name Indication (SNI)](https://datatracker.ietf.org/doc/html/rfc3546#section-3.1) extension when they connect.

When AWS IoT automatically registers a certificate or when a client presents a certificate in the `PENDING_ACTIVATION` status, AWS IoT publishes a message to the following MQTT topic:

`$aws/events/certificates/registered/caCertificateId`

Where `caCertificateId` is the ID of the CA certificate that issued the client certificate.

The message published to this topic has the following structure:

```
{
        "certificateId": "certificateId",
        "caCertificateId": "caCertificateId",
        "timestamp": timestamp,
        "certificateStatus": "PENDING_ACTIVATION",
        "awsAccountId": "awsAccountId",
        "certificateRegistrationTimestamp": "certificateRegistrationTimestamp"
}
```

You can create a rule that listens on this topic and performs some actions. We recommend that you create a Lambda rule that verifies the client certificate is not on a certificate revocation list (CRL), activates the certificate, and creates and attaches a policy to the certificate. The policy determines which resources the client can access. If the policy you are creating requires the client ID from the connecting devices, you can use rule's clientid() function to retrieve the client ID. An example rule definition can look like the following:

```
SELECT *,
   clientid() as clientid
from $aws/events/certificates/registered/caCertificateId
```

In this example, the rule subscribes to the JITR topic `$aws/events/certificates/registered/caCertificateID` and uses the clientid() function to retrieve the client ID. The rule then appends the client ID to the JITR payload. For more information about rule's clientid() function, see [clientid()](https://docs.aws.amazon.com//iot/latest/developerguide/iot-sql-functions.html#iot-sql-function-clientid).

For more information about how to create a Lambda rule that listens on the `$aws/events/certificates/registered/caCertificateID` topic and performs these actions, see [just-in-time registration of Client Certificates on AWS IoT](https://aws.amazon.com/blogs/iot/just-in-time-registration-of-device-certificates-on-aws-iot/).

If any error or exception occurs during the auto-registration of the client certificates, AWS IoT sends events or messages to your logs in CloudWatch Logs. For more information about setting up the logs for your account, see the [Amazon CloudWatch documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/).

# Manage client certificates
<a name="manage-device-cert"></a>

AWS IoT provides capabilities for you to manage client certificates.

**Topics**
+ [Activate or deactivate a client certificate](activate-or-deactivate-device-cert.md)
+ [Attach a thing or policy to a client certificate](attach-to-cert.md)
+ [Revoke a client certificate](revoke-ca-cert.md)
+ [Transfer a certificate to another account](transfer-cert.md)

# Activate or deactivate a client certificate
<a name="activate-or-deactivate-device-cert"></a>

AWS IoT verifies that a client certificate is active when it authenticates a connection.

You can create and register client certificates without activating them so they can't be used until you want to use them. You can also deactivate active client certificates to disable them temporarily. Finally, you can revoke client certificates to prevent them from any future use. 

## Activate a client certificate (console)
<a name="activate-device-cert-console"></a>

**To activate a client certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate that you want to activate, and open the option menu by using the ellipsis icon.

1. In the option menu, choose **Activate**.

The certificate should show as **Active** in the list of certificates.

## Deactivate a client certificate (console)
<a name="deactivate-device-cert-console"></a>

**To deactivate a client certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate that you want to deactivate, and open the option menu by using the ellipsis icon.

1. In the option menu, choose **Deactivate**.

The certificate should show as **Inactive** in the list of certificates.

## Activate a client certificate (CLI)
<a name="activate-device-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to activate a certificate.

```
aws iot update-certificate \
    --certificate-id certificateId \
    --new-status ACTIVE
```

If the command was successful, the certificate's status will be `ACTIVE`. Run [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html) to see the certificate's status.

```
aws iot describe-certificate \
    --certificate-id certificateId
```

## Deactivate a client certificate (CLI)
<a name="deactivate-device-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to deactivate a certificate.

```
aws iot update-certificate \
    --certificate-id certificateId \
    --new-status INACTIVE
```

If the command was successful, the certificate's status will be `INACTIVE`. Run [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html) to see the certificate's status.

```
aws iot describe-certificate \
    --certificate-id certificateId
```

# Attach a thing or policy to a client certificate
<a name="attach-to-cert"></a>

When you create and register a certificate separate from an AWS IoT thing, it will not have any policies that authorize any AWS IoT operations, nor will it be associated with any AWS IoT thing object. This section describes how to add these relationships to a registered certificate.

**Important**  
To complete these procedures, you must have already created the thing or policy that you want to attach to the certificate.

The certificate authenticates a device with AWS IoT so that it can connect. Attaching the certificate to a thing resource establishes the relationship between the device (by way of the certificate) and the thing resource. To authorize the device to perform AWS IoT actions, such as to allow the device to connect and publish messages, an appropriate policy must be attached to the device's certificate. 

## Attach a thing to a client certificate (console)
<a name="attach-to-cert-thing-console"></a>

You will need the name of the thing object to complete this procedure.

**To attach a thing object to a registered certificate**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate to which you want to attach a policy, open the certificate's option menu by choosing the ellipsis icon, and choose **Attach thing**.

1. In the pop-up, locate the name of the thing you want to attach to the certificate, choose its check box, and choose **Attach**.

The thing object should now appear in the list of things on the certificate's details page.

## Attach a policy to a client certificate (console)
<a name="attach-to-cert-policy-console"></a>

You will need the name of the policy object to complete this procedure.

**To attach a policy object to a registered certificate**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate to which you want to attach a policy, open the certificate's option menu by choosing the ellipsis icon, and choose **Attach policy**. 

1. In the pop-up, locate the name of the policy you want to attach to the certificate, choose its check box, and choose **Attach**.

The policy object should now appear in the list of policies on the certificate's details page.

## Attach a thing to a client certificate (CLI)
<a name="attach-to-cert-thing-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-thing-principal.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-thing-principal.html) command to attach a thing object to a certificate.

```
aws iot attach-thing-principal \
    --principal certificateArn \
    --thing-name thingName
```

## Attach a policy to a client certificate (CLI)
<a name="attach-to-cert-policy-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-policy.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-policy.html) command to attach a policy object to a certificate.

```
aws iot attach-policy \
    --target certificateArn \
    --policy-name policyName
```

# Revoke a client certificate
<a name="revoke-ca-cert"></a>

If you detect suspicious activity on a registered client certificate, you can revoke it so that it can't be used again.

**Note**  
Once a certificate is revoked, it's status can't be changed. That is, the certificate status can't be changed to `Active` or any other status.

## Revoke a client certificate (console)
<a name="revoke-device-cert-console"></a>

**To revoke a client certificate using the AWS IoT console**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

1. In the list of certificates, locate the certificate that you want to revoke, and open the option menu by using the ellipsis icon.

1. In the option menu, choose **Revoke**.

If the certificate was successfully revoked, it will show as **Revoked** in the list of certificates.

## Revoke a client certificate (CLI)
<a name="revoke-device-cert-cli"></a>

The AWS CLI provides the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to revoke a certificate.

```
aws iot update-certificate \
    --certificate-id certificateId \
    --new-status REVOKED
```

If the command was successful, the certificate's status will be `REVOKED`. Run [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html) to see the certificate's status.

```
aws iot describe-certificate \
    --certificate-id certificateId
```

# Transfer a certificate to another account
<a name="transfer-cert"></a>

X.509 certificates that belong to one AWS account can be transferred to another AWS account.

**To transfer an X.509 certificate from one AWS account to another**

1. [Begin a certificate transfer](#transfer-cert-init)

   The certificate must be deactivated and detached from all policies and things before initiating the transfer.

1. [Accept or reject a certificate transfer](#transfer-cert-accept)

   The receiving account must explicitly accept or reject the transferred certificate. After the receiving account accepts the certificate, the certificate must be activated before use.

1. [Cancel a certificate transfer](#transfer-cert-cancel)

   The originating account can cancel a transfer, if the certificate has not been accepted.

## Begin a certificate transfer
<a name="transfer-cert-init"></a>

You can begin to transfer a certificate to another AWS account by using the [AWS IoT console](https://console.aws.amazon.com/iot/home) or the AWS CLI.

### Begin a certificate transfer (console)
<a name="transfer-cert-init-console"></a>

To complete this procedure, you'll need the ID of the certificate that you want to transfer.

Do this procedure from the account with the certificate to transfer.

**To begin to transfer a certificate to another AWS account**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

   Choose the certificate with an **Active** or **Inactive** status that you want to transfer and open its details page.

1. On the certificate's **Details** page, in the **Actions** menu, if the **Deactivate** option is available, choose the **Deactivate** option to deactivate the certificate.

1. On the certificate's **Details** page, in the left menu, choose **Policies**.

1. On the certificate's **Policies** page, if there are any policies attached to the certificate, detach each one by opening the policy's options menu and choosing **Detach**.

   The certificate must not have any attached policies before you continue.

1. On the certificate's **Policies** page, in the left menu, choose **Things**.

1. On the certificate's **Things** page, if there are any things attached to the certificate, detach each one by opening the thing's options menu and choosing **Detach**.

   The certificate must not have any attached things before you continue.

1. On the certificate's **Things** page, in the left menu, choose **Details**.

1. On the certificate's **Details** page, in the **Actions** menu, choose **Start transfer** to open the **Start transfer** dialog box.

1. In the **Start transfer** dialog box, enter the AWS account number of the account to receive the certificate and an optional short message.

1. Choose **Start transfer** to transfer the certificate.

The console should display a message that indicates the success or failure of the transfer. If the transfer was started, the certificate's status is updated to **Transferred**.

### Begin a certificate transfer (CLI)
<a name="transfer-cert-init-cli"></a>

To complete this procedure, you'll need the *certificateId* and the *certificateArn* of the certificate that you want to transfer.

Do this procedure from the account with the certificate to transfer.

**To begin to transfer a certificate to another AWS account**

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html) command to deactivate the certificate.

   ```
   aws iot update-certificate --certificate-id certificateId --new-status INACTIVE
   ```

1. Detach all policies.

   1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-attached-policies.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-attached-policies.html) command to list the policies attached to the certificate.

      ```
      aws iot list-attached-policies --target certificateArn
      ```

   1. For each attached policy, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-policy.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-policy.html) command to detach the policy.

      ```
      aws iot detach-policy --target certificateArn --policy-name policy-name
      ```

1. Detach all things.

   1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-principal-things.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-principal-things.html) command to list the things attached to the certificate.

      ```
      aws iot list-principal-things --principal certificateArn
      ```

   1. For each attached thing, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-thing-principal.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-thing-principal.html) command to detach the thing.

      ```
      aws iot detach-thing-principal --principal certificateArn --thing-name thing-name
      ```

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/transfer-certificate.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/transfer-certificate.html) command to start the certificate transfer.

   ```
   aws iot transfer-certificate --certificate-id certificateId --target-aws-account account-id
   ```

## Accept or reject a certificate transfer
<a name="transfer-cert-accept"></a>

You can accept or reject a certificate transferred to you AWS account from another AWS account by using the [AWS IoT console](https://console.aws.amazon.com/iot/home) or the AWS CLI.

### Accept or reject a certificate transfer (console)
<a name="transfer-cert-accept-console"></a>

To complete this procedure, you'll need the ID of the certificate that was transferred to your account.

Do this procedure from the account receiving the certificate that was transferred.

**To accept or reject a certificate that was transferred to your AWS account**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

   Choose the certificate with a status of **Pending transfer** that you want to accept or reject and open its details page.

1. On the certificate's **Details** page, in the **Actions** menu,
   + To accept the certificate, choose **Accept transfer**.
   + To not accept the certificate, choose **Reject transfer**.

### Accept or reject a certificate transfer (CLI)
<a name="transfer-cert-accept-cli"></a>

To complete this procedure, you'll need the *certificateId* of the certificate transfer that you want to accept or reject.

Do this procedure from the account receiving the certificate that was transferred.

**To accept or reject a certificate that was transferred to your AWS account**

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/accept-certificate-transfer.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/accept-certificate-transfer.html) command to accept the certificate.

   ```
   aws iot accept-certificate-transfer --certificate-id certificateId
   ```

1. Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/reject-certificate-transfer.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/reject-certificate-transfer.html) command to reject the certificate.

   ```
   aws iot reject-certificate-transfer --certificate-id certificateId
   ```

## Cancel a certificate transfer
<a name="transfer-cert-cancel"></a>

You can cancel a certificate transfer before it has been accepted by using the [AWS IoT console](https://console.aws.amazon.com/iot/home) or the AWS CLI.

### Cancel a certificate transfer (console)
<a name="transfer-cert-cancel-console"></a>

To complete this procedure, you'll need the ID of the certificate transfer that you want to cancel.

Do this procedure from the account that initiated the certificate transfer.

**To cancel a certificate transfer**

1. Sign in to the AWS Management Console and open the [AWS IoT console](https://console.aws.amazon.com/iot/home).

1. In the left navigation pane, choose **Secure**, choose **Certificates**.

   Choose the certificate with **Transferred** status whose transfer you want to cancel and open its options menu.

1. On the certificate's options menu, choose the **Revoke transfer** option to cancel the certificate transfer.
**Important**  
Be careful not to mistake the **Revoke transfer** option with the **Revoke** option.  
The **Revoke transfer** option cancels the certificate transfer, while the **Revoke** option makes the certificate irreversibly unusable by AWS IoT. 

### Cancel a certificate transfer (CLI)
<a name="transfer-cert-cancel-cli"></a>

To complete this procedure, you'll need the *certificateId* of the certificate transfer that you want to cancel.

Do this procedure from the account that initiated the certificate transfer.

Use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-certificate-transfer.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-certificate-transfer.html) command to cancel the certificate transfer.

```
aws iot cancel-certificate-transfer --certificate-id certificateId
```

# Custom client certificate validation
<a name="customize-client-auth"></a>

AWS IoT Core supports custom client certificate validation for X.509 client certificates, which enhances client authentication management. This certificate validation method is also known as pre-authentication certificate checks, in which you evaluate client certificates based on your own criteria (defined in a Lambda function) and revoke client certificates or the certificates' signing certificate authority (CA) certificate to prevent clients to connect to AWS IoT Core. For example, you can create your own certificate revocation checks that validate the certificates' status against validation authorities that support [Online Certificate Status Protocol (OCSP)](https://en.wikipedia.org/wiki/Online_Certificate_Status_Protocol) or [Certificate Revocation Lists (CRL)](https://en.wikipedia.org/wiki/Certificate_revocation_list) endpoints, and prevent connections for clients with revoked certificates. The criteria used to evaluate client certificates are defined in a Lambda function (also known as pre-authentication Lambda). You must use the endpoints set in domain configurations and the[ authentication type](protocols.md#connection-protocol-auth-mode) must be X.509 certificate. In addition, clients must provide the [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) extension when connecting to AWS IoT Core.

**Note**  
This feature is not supported in the AWS GovCloud (US) Regions.

**Topics**
+ [Step 1: Register your X.509 client certificates with AWS IoT Core](#client-auth-cert-verification)
+ [Step 2: Create a Lambda function](#customize-client-auth-lambda)
+ [Step 3: Authorize AWS IoT to invoke your Lambda function](#customize-client-configuration-grant-permission)
+ [Step 4: Set authentication configuration for a domain](#customize-client-configuration)

## Step 1: Register your X.509 client certificates with AWS IoT Core
<a name="client-auth-cert-verification"></a>

If you haven't done this already, register and activate your [X.509 client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html) with AWS IoT Core. Otherwise, skip to the next step.

To register and activate your client certificates with AWS IoT Core, follow the steps:

1. If you [create client certificates directly with AWS IoT](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-create.html). These client certificates will be automatically registered with AWS IoT Core.

1. If you [create your own client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-your-own.html), follow [these instructions to register them with AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/register-device-cert.html).

1. To activate your client certificates, follow [these instructions](https://docs.aws.amazon.com//iot/latest/developerguide/activate-or-deactivate-device-cert.html).

## Step 2: Create a Lambda function
<a name="customize-client-auth-lambda"></a>

You need to create a Lambda function that will perform certificate verification and be called for every client connect attempt for the configured endpoint. When creating this Lambda function, follow the general guidance from [Create your first Lambda function](https://docs.aws.amazon.com//lambda/latest/dg/getting-started.html). Additionally, ensure that the Lambda function adheres to the expected request and response formats as follows:

**Lambda function event example**

```
{
	"connectionMetadata": {
		"id": "string"
	},
	"principalId": "string",
	"serverName": "string",
	"clientCertificateChain": [
		"string",
		"string"
	]
}
```

`connectionMetadata`  
Metadata or additional information related to the client's connection to AWS IoT Core.

`principalId`  
The principal identifier associated with the client in the TLS connection.

`serverName`  
The [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) hostname string. AWS IoT Core requires devices to send the [SNI extension](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field.

`clientCertificateChain`  
The array of strings that represents the client's X.509 certificate chain. 

**Lambda function response example**

```
{
	"isAuthenticated": "boolean"
}
```

`isAuthenticated`  
A Boolean value that indicates whether the request is authenticated.

**Note**  
In the Lambda response, `isAuthenticated` must be `true` to proceed to further authentication and authorization. Otherwise, the IoT client certificate can be disabled and custom authentication with X.509 client certificates can be blocked for further authentication and authorization.

## Step 3: Authorize AWS IoT to invoke your Lambda function
<a name="customize-client-configuration-grant-permission"></a>

After creating the Lambda function, you must grant permission for AWS IoT to invoke it, by using the [add-permission](https://docs.aws.amazon.com//cli/latest/reference/lambda/add-permission.html) CLI command. Note that this Lambda function will be invoked for every connect attempt to your configured endpoint. For more information, see [Authorizing AWS IoT to invoke your Lambda function](custom-auth-authorize.md).

## Step 4: Set authentication configuration for a domain
<a name="customize-client-configuration"></a>

The following section describes how to set authentication configuration for a custom domain using the AWS CLI.

### Set client certificate configuration for a domain (CLI)
<a name="customize-client-auth-cli"></a>

If you don't have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html) CLI command to create one. If you already have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html) CLI command to update the client certificate configuration for a domain. You must add the ARN of the Lambda function that you've created in the previous step.

```
aws iot create-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type AWS_X509|CUSTOM_AUTH_X509 \
    --application-protocol SECURE_MQTT|HTTPS \
    --client-certificate-config 'clientCertificateCallbackArn":"arn:aws:lambda:us-east-2:123456789012:function:my-function:1"}'
```

```
aws iot update-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type AWS_X509|CUSTOM_AUTH_X509 \
    --application-protocol SECURE_MQTT|HTTPS \
    --client-certificate-config '{"clientCertificateCallbackArn":"arn:aws:lambda:us-east-2:123456789012:function:my-function:1"}'
```

`domain-configuration-name`  
The name of the domain configuration.

`authentication-type`  
The authentication type of the domain configuration. For more information, see [choosing an authentication type](protocols.md#connection-protocol-auth-mode).

`application-protocol`  
The application protocol which devices use to communicate with AWS IoT Core. For more information, see [choosing an application protocol](protocols.md#protocol-selection).

`client-certificate-config`  
An object that specifies the client authentication configuration for a domain.

`clientCertificateCallbackArn`  
The Amazon Resource Name (ARN) of the Lambda function that AWS IoT invokes in TLS layer when new connection is being established. To customize client authentication to perform custom client certificate validation, you must add the ARN of the Lambda function that you've created in the previous step.

For more information, see [CreateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_CreateDomainConfiguration.html) and [UpdateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_UpdateDomainConfiguration.html) from the *AWS IoT API Reference*. For more information about domain configurations, see [Domain configurations](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable.html).

# IAM users, groups, and roles
<a name="iam-users-groups-roles"></a>

IAM users, groups, and roles are the standard mechanisms for managing identity and authentication in AWS. You can use them to connect to AWS IoT HTTP interfaces using the AWS SDK and AWS CLI.

IAM roles also allow AWS IoT to access other AWS resources in your account on your behalf. For example, if you want to have a device publish its state to a DynamoDB table, IAM roles allow AWS IoT to interact with Amazon DynamoDB. For more information, see [IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html).

For message broker connections over HTTP, AWS IoT authenticates users, groups, and roles using the Signature Version 4 signing process. For information, see [Signing AWS API Requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html).

When authenticating requests using query parameters with [temporary security credentials provided by AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html), do not include `X-Amz-Security-Token` in the canonical query string when calculating the signature. Instead, append `X-Amz-Security-Token` as a query parameter after the signature has been computed. This differs from some other AWS services that require the security token to be part of the canonical request. For more information, see [ Signing requests with temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#temporary-security-credentials).

**Note**  
The AWS IoT Device SDKs handle this signing behavior automatically. If you are implementing custom signing code, refer to the SDK source for reference:  
[AWS IoT Device SDK for Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/awsiot/mqtt_connection_builder.py) — see `websockets_with_default_aws_signing()`, which sets `omit_session_token=True`
[AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/sdk/src/main/java/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.java) — see `setOmitSessionToken(true)`

When using AWS Signature Version 4 with AWS IoT, clients must support the following in their TLS implementation:
+ TLS 1.2
+ SHA-256 RSA certificate signature validation
+ One of the cipher suites from the TLS cipher suite support section

For information, see [Identity and access management for AWS IoT](security-iam.md).

# Amazon Cognito identities
<a name="cognito-identities"></a>

Amazon Cognito Identity enables you to create temporary, limited privilege AWS credentials for use in mobile and web applications. When you use Amazon Cognito Identity, create identity pools that create unique identities for your users and authenticate them with identity providers like Login with Amazon, Facebook, and Google. You can also use Amazon Cognito identities with your own developer authenticated identities. For more information, see [ Amazon Cognito Identity](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html).

To use Amazon Cognito Identity, define an Amazon Cognito identity pool that is associated with an IAM role. The IAM role is associated with an IAM policy that grants identities from your identity pool permission to access AWS resources like calling AWS services.

Amazon Cognito Identity creates unauthenticated and authenticated identities. Unauthenticated identities are used for guest users in a mobile or web application who want to use the app without signing in. Unauthenticated users are granted only those permissions specified in the IAM policy associated with the identity pool.

When you use authenticated identities, in addition to the IAM policy attached to the identity pool, you must attach an AWS IoT policy to an Amazon Cognito Identity. To attach an AWS IoT policy, use the [ AttachPolicy](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachPolicy.html) API and give permissions to an individual user of your AWS IoT application. You can use the AWS IoT policy to assign fine-grained permissions for specific customers and their devices.

Authenticated and unauthenticated users are different identity types. If you don't attach an AWS IoT policy to the Amazon Cognito Identity, an authenticated user fails authorization in AWS IoT and doesn't have access to AWS IoT resources and actions. For more information about creating policies for Amazon Cognito identities, see [Publish/Subscribe policy examples](pub-sub-policy.md) and [Authorization with Amazon Cognito identities](cog-iot-policies.md).

![\[Application accessing a device with Amazon Cognito Identity.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/device-cognito.png)


# Custom authentication and authorization
<a name="custom-authentication"></a>

 AWS IoT Core lets you define custom authorizers so that you can manage your own client authentication and authorization. This is useful when you need to use authentication mechanisms other than the ones that AWS IoT Core natively supports. (For more information about the natively supported mechanisms, see [Client authentication](client-authentication.md)).  

 For example, if you are migrating existing devices in the field to AWS IoT Core and these devices use a custom bearer token or MQTT user name and password to authenticate, you can migrate them to AWS IoT Core without having to provision new identities for them. You can use custom authentication with any of the communication protocols that AWS IoT Core supports. For more information about the protocols that AWS IoT Core supports, see [Device communication protocols](protocols.md). 

**Topics**
+ [Understanding the custom authentication workflow](custom-authorizer.md)
+ [Creating and managing custom authorizers (CLI)](config-custom-auth.md)
+ [Custom authentication with X.509 client certificates](custom-auth-509cert.md)
+ [Connecting to AWS IoT Core by using custom authentication](custom-auth.md)
+ [Troubleshooting your authorizers](custom-auth-troubleshooting.md)

# Understanding the custom authentication workflow
<a name="custom-authorizer"></a>

Custom authentication enables you to define how to authenticate and authorize clients by using [authorizer resources](https://docs.aws.amazon.com/iot/latest/apireference/API_AuthorizerDescription.html).  Each authorizer contains a reference to a customer-managed Lambda function, an optional public key for validating device credentials, and additional configuration information. The following diagram illustrates the authorization workflow for custom authentication in AWS IoT Core.

![\[Custom authorization workflow for custom authentication in AWS IoT Core.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/custom-authentication.png)


## AWS IoT Core custom authentication and authorization workflow
<a name="custom-authentication-workflow"></a>

The following list explains each step in the custom authentication and authorization workflow.

1. A device connects to a customer’s AWS IoT Core data endpoint by using one of the supported [Device communication protocols](protocols.md). The device passes credentials in either the request’s header fields or query parameters (for the HTTP Publish or MQTT over WebSockets protocols), or in the user name and password field of the MQTT CONNECT message (for the MQTT and MQTT over WebSockets protocols).

1. AWS IoT Core checks for one of two conditions:
   + The incoming request specifies an authorizer.
   + The AWS IoT Core data endpoint receiving the request has a default authorizer configured for it.

   If AWS IoT Core finds an authorizer in either of these ways, AWS IoT Core triggers the Lambda function associated with the authorizer.

1.  (Optional) If you've enabled token signing, AWS IoT Core validates the request signature by using the public key stored in the authorizer before triggering the Lambda function. If validation fails, AWS IoT Core stops the request without invoking the Lambda function.  

1. The Lambda function receives the credentials and connection metadata in the request and makes an authentication decision.

1. The Lambda function returns the results of the authentication decision and an AWS IoT Core policy document that specifies what actions are allowed in the connection. The Lambda function also returns information that specifies how often AWS IoT Core revalidates the credentials in the request by invoking the Lambda function.

1. AWS IoT Core evaluates activity on the connection against the policy it has received from the Lambda function.

1. After the connection is established and your custom authorizer Lambda is initially invoked, the next invocation can be delayed for up to 5 minutes on idle connections without any MQTT operations. After that, subsequent invocations will follow the refresh interval in your custom authorizer Lambda. This approach can prevent excessive invocations that could exceed the Lambda concurrency limit of your AWS account.

## Scaling considerations
<a name="custom-authentication-scaling"></a>

 Because a Lambda function handles authentication and authorization for your authorizer, the function is subject to Lambda pricing and service limits, such as concurrent execution rate. For more information about Lambda pricing, see [Lambda Pricing](https://aws.amazon.com/lambda/pricing/). You can manage the load on your Lambda function by adjusting the `refreshAfterInSeconds` and `disconnectAfterInSeconds` parameters in your Lambda function response. For more information about the contents of your Lambda function response, see [Defining your Lambda function](custom-auth-lambda.md).

**Note**  
If you leave signing enabled, you can prevent excessive triggering of your Lambda by unrecognized clients. Consider this before you disable signing in your authorizer.

**Note**  
The Lambda function timeout limit for custom authorizer is 5 seconds.

# Creating and managing custom authorizers (CLI)
<a name="config-custom-auth"></a>

AWS IoT Core implements custom authentication and authorization schemes by using custom authorizers. A custom authorizer is an AWS IoT Core resource that gives you the flexibility to define and implement the rules and policies based on your specific requirements. To create a custom authorizer with step-by-step instructions, see [Tutorial: Creating a custom authorizer for AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/custom-auth-tutorial.html).

Each authorizer consists of the following components: 
+  *Name*: A unique user-defined string that identifies the authorizer.
+  *Lambda function ARN*: The Amazon Resource Name (ARN) of the Lambda function that implements the authorization and authentication logic.  
+  *Token key name*: The key name used to extract the token from the HTTP headers, query parameters, or MQTT CONNECT user name in order to perform signature validation. This value is required if signing is enabled in your authorizer. 
+  *Signing disabled flag (optional)*: A Boolean value that specifies whether to disable the signing requirement on credentials. This is useful for scenarios where signing the credentials doesn't make sense, such as authentication schemes that use MQTT user name and password. The default value is `false`, so signing is enabled by default. 
+  *Token signing public key*: The public key that AWS IoT Core uses to validate the token signature. Its minimum length is 2,048 bits. This value is required if signing is enabled in your authorizer.  

Lambda charges you for the number of times your Lambda function runs and for the amount of time it takes for the code in your function to execute. For more information about Lambda pricing, see [Lambda Pricing](https://aws.amazon.com/lambda/pricing/). For more information about creating Lambda functions, see the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/).

**Note**  
If you leave signing enabled, you can prevent excessive triggering of your Lambda by unrecognized clients. Consider this before you disable signing in your authorizer.

**Note**  
The Lambda function timeout limit for custom authorizer is 5 seconds.

**Topics**
+ [Defining your Lambda function](custom-auth-lambda.md)
+ [Creating an authorizer](custom-auth-create-authorizer.md)
+ [Authorizing AWS IoT to invoke your Lambda function](custom-auth-authorize.md)
+ [Testing your authorizers](custom-auth-testing.md)
+ [Managing custom authorizers](custom-auth-manage.md)

# Defining your Lambda function
<a name="custom-auth-lambda"></a>

 When AWS IoT Core invokes your authorizer, it triggers the associated Lambda associated with the authorizer with an event that contains the following JSON object. The example JSON object contains all of the possible fields. Any fields that aren't relevant to the connection request aren't included.

```
{
    "token" :"aToken",
    "signatureVerified": Boolean, // Indicates whether the device gateway has validated the signature.
    "protocols": ["tls", "http", "mqtt"], // Indicates which protocols to expect for the request.
    "protocolData": {
        "tls" : {
            "serverName": "serverName" // The server name indication (SNI) host_name string.
        },
        "http": {
            "headers": {
                "#{name}": "#{value}"
            },
            "queryString": "?#{name}=#{value}"
        },
        "mqtt": {
            "username": "myUserName",
            "password": "myPassword", // A base64-encoded string.
            "clientId": "myClientId" // Included in the event only when the device sends the value.
        }
    },
    "connectionMetadata": {
        "id": UUID // The connection ID. You can use this for logging.
    },
}
```

 The Lambda function should use this information to authenticate the incoming connection and decide what actions are permitted in the connection. The function should send a response that contains the following values. 
+  `isAuthenticated`: A Boolean value that indicates whether the request is authenticated.
+  `principalId`: An alphanumeric string that acts as an identifier for the token sent by the custom authorization request. The value must be an alphanumeric string with at least one, and no more than 128, characters and match this regular expression (regex) pattern: `([a-zA-Z0-9]){1,128}`. Special characters that are not alphanumeric are not allowed for use with the `principalId` in AWS IoT Core. Refer to the documentation for other AWS services if non-alphanumeric special characters are allowed for the `principalId`.
+  `policyDocuments`: A list of JSON-formatted AWS IoT Core policy documents For more information about creating AWS IoT Core policies, see [AWS IoT Core policies](iot-policies.md). The maximum number of policy documents is 10 policy documents. Each policy document can contain a maximum of 2,048 characters.
+  `disconnectAfterInSeconds`: An integer that specifies the maximum duration (in seconds) of the connection to the AWS IoT Core gateway. The minimum value is 300 seconds, and the maximum value is 86,400 seconds. The default value is 86,400.
**Note**  
The value of `disconnectAfterInSeconds` (returned by the Lambda function) is set when the connection establishes. This value cannot be modified during subsequent policy refresh Lambda invocations.
+  `refreshAfterInSeconds`: An integer that specifies the interval between policy refreshes. When this interval passes, AWS IoT Core invokes the Lambda function to allow for policy refreshes. The minimum value is 300 seconds, and the maximum value is 86,400 seconds. 

  The following JSON object contains an example of a response that your Lambda function can send. 

 **\$1 "isAuthenticated":true, //A Boolean that determines whether client can connect. "principalId": "xxxxxxxx",  //A string that identifies the connection in logs. "disconnectAfterInSeconds": 86400,  "refreshAfterInSeconds": 300,   "policyDocuments": [       \$1         "Version": "2012-10-17",         "Statement": [            \$1               "Action": "iot:Publish",               "Effect": "Allow",               "Resource": "arn:aws:iot:us-east-1:<your\$1aws\$1account\$1id>:topic/customauthtesting"             \$1          ]        \$1     ] \$1**

 The `policyDocument` value must contain a valid AWS IoT Core policy document. For more information about AWS IoT Core policies, see [AWS IoT Core policies](iot-policies.md).  In MQTT over TLS and MQTT over WebSockets connections, AWS IoT Core caches this policy for the interval specified in the value of the `refreshAfterInSeconds` field. In the case of HTTP connections the Lambda function is called for every authorization request unless your device is using HTTP persistent connections (also called HTTP keep-alive or HTTP connection reuse) you can choose to enable caching when configuring the authorizer. During this interval, AWS IoT Core authorizes actions in an established connection against this cached policy without triggering your Lambda function again. If failures occur during custom authentication, AWS IoT Core terminates the connection. AWS IoT Core also terminates the connection if it has been open for longer than the value specified in the `disconnectAfterInSeconds`parameter. 

 The following JavaScript contains a sample Node.js Lambda function that looks for a password in the MQTT Connect message with a value of `test` and returns a policy that grants permission to connect to AWS IoT Core with a client named `myClientName` and publish to a topic that contains the same client name. If it doesn't find the expected password, it returns a policy that denies those two actions. 

```
// A simple Lambda function for an authorizer. It demonstrates 
// how to parse an MQTT password and generate a response.

exports.handler = function(event, context, callback) { 
    var uname = event.protocolData.mqtt.username;
    var pwd = event.protocolData.mqtt.password;
    var buff = new Buffer(pwd, 'base64');
    var passwd = buff.toString('ascii');
    switch (passwd) { 
        case 'test': 
            callback(null, generateAuthResponse(passwd, 'Allow')); 
            break;
        default: 
            callback(null, generateAuthResponse(passwd, 'Deny'));  
    }
};

// Helper function to generate the authorization response.
var generateAuthResponse = function(token, effect) { 
    var authResponse = {}; 
    authResponse.isAuthenticated = true; 
    authResponse.principalId = 'TEST123'; 
    
    var policyDocument = {}; 
    policyDocument.Version = '2012-10-17';		 	 	 
    policyDocument.Statement = []; 
    var publishStatement = {}; 
    var connectStatement = {};
    connectStatement.Action = ["iot:Connect"];
    connectStatement.Effect = effect;
    connectStatement.Resource = ["arn:aws:iot:us-east-1:123456789012:client/myClientName"];
    publishStatement.Action = ["iot:Publish"]; 
    publishStatement.Effect = effect; 
    publishStatement.Resource = ["arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"]; 
    policyDocument.Statement[0] = connectStatement;
    policyDocument.Statement[1] = publishStatement; 
    authResponse.policyDocuments = [policyDocument]; 
    authResponse.disconnectAfterInSeconds = 3600; 
    authResponse.refreshAfterInSeconds = 300;
    
    return authResponse; 
}
```

 The preceding Lambda function returns the following JSON when it receives the expected password of `test` in the MQTT Connect message. The values of the `password` and `principalId` properties will be the values from the MQTT Connect message.

```
{
  "password": "password",
  "isAuthenticated": true,
  "principalId": "principalId",
  "policyDocuments": [
    {
      "Version": "2012-10-17",		 	 	 
      "Statement": [
        {
          "Action": "iot:Connect",
          "Effect": "Allow",
          "Resource": "*"
        },
        {
          "Action": "iot:Publish",
          "Effect": "Allow",
          "Resource": "arn:aws:iot:region:accountId:topic/telemetry/${iot:ClientId}"
        },
        {
          "Action": "iot:Subscribe",
          "Effect": "Allow",
          "Resource": "arn:aws:iot:region:accountId:topicfilter/telemetry/${iot:ClientId}"
        },
        {
          "Action": "iot:Receive",
          "Effect": "Allow",
          "Resource": "arn:aws:iot:region:accountId:topic/telemetry/${iot:ClientId}"
        }
      ]
    }
  ],
  "disconnectAfterInSeconds": 3600,
  "refreshAfterInSeconds": 300
}
```

# Creating an authorizer
<a name="custom-auth-create-authorizer"></a>

 You can create an authorizer by using the [CreateAuthorizer API](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateAuthorizer.html). The following example describes the command. 

```
aws iot create-authorizer
--authorizer-name MyAuthorizer
--authorizer-function-arn arn:aws:lambda:us-west-2:<account_id>:function:MyAuthorizerFunction  //The ARN of the Lambda function.
[--token-key-name MyAuthorizerToken //The key used to extract the token from headers.
[--token-signing-public-keys FirstKey=
 "-----BEGIN PUBLIC KEY-----
  [...insert your public key here...] 
  -----END PUBLIC KEY-----"
[--status ACTIVE]
[--tags <value>]
[--signing-disabled | --no-signing-disabled]
```

You can use the `signing-disabled` parameter to opt out of signature validation for each invocation of your authorizer. We strongly recommend that you do not disable signing unless you have to. Signature validation protects you against excessive invocations of your Lambda function from unknown devices. You can't update the `signing-disabled` status of an authorizer after you create it. To change this behavior, you must create another custom authorizer with a different value for the `signing-disabled` parameter. 

Values for the `tokenKeyName` and `tokenSigningPublicKeys` parameters are optional if you have disabled signing. They are required values if signing is enabled. 

After you create your Lambda function and the custom authorizer, you must explicitly grant the AWS IoT Core service permission to invoke the function on your behalf. You can do this with the following command. 

**Note**  
The default IoT endpoint might not support using custom authorizers with Lambda functions. Instead, you can use domain configurations to define a new endpoint and then specify that endpoint for the custom authorizer.

```
aws lambda add-permission --function-name <lambda_function_name>
--principal iot.amazonaws.com --source-arn <authorizer_arn>
--statement-id Id-123 --action "lambda:InvokeFunction"
```

# Authorizing AWS IoT to invoke your Lambda function
<a name="custom-auth-authorize"></a>

In this section, you'll grant the permission of the custom authorizer resource that you just created to run the Lambda function. To grant the permission, you can use the [add-permission](https://docs.aws.amazon.com//cli/latest/reference/lambda/add-permission.html) CLI command.

**Grant permission to your Lambda function using the AWS CLI**

1. After inserting your values, enter the following command. Note that the `statement-id` value must be unique. Replace `Id-1234` with the exact value you have, otherwise, you might get a `ResourceConflictException` error.

   ```
   aws lambda add-permission  \
   --function-name "custom-auth-function" \
   --principal "iot.amazonaws.com" \
   --action "lambda:InvokeFunction" \
   --statement-id "Id-1234" \
   --source-arn authorizerArn
   ```

1. If the command succeeds, it returns a permission statement, such as this example. You can continue to the next section to test the custom authorizer.

   ```
   {
       "Statement": "{\"Sid\":\"Id-1234\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"iot.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:Region:57EXAMPLE833:function:custom-auth-function\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:lambda:Region:57EXAMPLE833:function:custom-auth-function\"}}}"
   }
   ```

   If the command doesn't succeed, it returns an error, such as this example. You'll need to review and correct the error before you continue.

   ```
   An error occurred (AccessDeniedException) when calling the AddPermission operation: User: arn:aws:iam::57EXAMPLE833:user/EXAMPLE-1 is not authorized to perform: lambda:AddPer
   mission on resource: arn:aws:lambda:Region:57EXAMPLE833:function:custom-auth-function
   ```

# Testing your authorizers
<a name="custom-auth-testing"></a>

 You can use the [TestInvokeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_TestInvokeAuthorizer.html) API to test the invocation and return values of your authorizer. This API enables you to specify protocol metadata and test the signature validation in your authorizer.

The following tabs show how to use the AWS CLI to test your authorizer.

------
#### [ Unix-like ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER \
--token TOKEN_VALUE --token-signature TOKEN_SIGNATURE
```

------
#### [ Windows CMD ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER ^
--token TOKEN_VALUE --token-signature TOKEN_SIGNATURE
```

------
#### [ Windows PowerShell ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER `
--token TOKEN_VALUE --token-signature TOKEN_SIGNATURE
```

------

The value of the `token-signature` parameter is the signed token. To learn how to obtain this value, see [Signing the token](custom-auth.md#custom-auth-token-signature).

If your authorizer takes a user name and password, you can pass this information by using the `--mqtt-context` parameter. The following tabs show how to use the `TestInvokeAuthorizer` API to send a JSON object that contains a user name, password, and client name to your custom authorizer.

------
#### [ Unix-like ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER  \
--mqtt-context '{"username": "USER_NAME", "password": "dGVzdA==", "clientId":"CLIENT_NAME"}'
```

------
#### [ Windows CMD ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER  ^
--mqtt-context '{"username": "USER_NAME", "password": "dGVzdA==", "clientId":"CLIENT_NAME"}'
```

------
#### [ Windows PowerShell ]

```
aws iot test-invoke-authorizer --authorizer-name NAME_OF_AUTHORIZER  `
--mqtt-context '{"username": "USER_NAME", "password": "dGVzdA==", "clientId":"CLIENT_NAME"}'
```

------

The password must be base64-encoded. The following example shows how to encode a password in a Unix-like environment.

```
echo -n PASSWORD | base64
```

# Managing custom authorizers
<a name="custom-auth-manage"></a>

 You can manage your authorizers by using the following APIs. 
+ [ListAuthorizers](https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuthorizers.html): Show all authorizers in your account.
+  [DescribeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuthorizer.html): Displays properties of the specified authorizer. These values include creation date, last modified date, and other attributes.
+ [SetDefaultAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_SetDefaultAuthorizer.html): Specifies the default authorizer for your AWS IoT Core data endpoints. AWS IoT Core uses this authorizer if a device doesn't pass AWS IoT Core credentials and doesn't specify an authorizer. For more information about using AWS IoT Core credentials, see [Client authentication](client-authentication.md).
+ [UpdateAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateAuthorizer.html):  Changes the status, token key name, or public keys for the specified authorizer.
+  [DeleteAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteAuthorizer.html): Deletes the specified authorizer. 

**Note**  
 You can't update an authorizer's signing requirement. This means that you can't disable signing in an existing authorizer that requires it. You also can't require signing in an existing authorizer that doesn't require it. 

# Custom authentication with X.509 client certificates
<a name="custom-auth-509cert"></a>

When connecting devices to AWS IoT Core, you have multiple [authentication types](protocols.md#connection-protocol-auth-mode) available. You can use [X.509 client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html) that can be used to authenticate client and device connections, or define [custom authorizers](https://docs.aws.amazon.com//iot/latest/developerguide/custom-authentication.html) to manage your own client authentication and authorization logic. This topic covers how to use custom authentication with X.509 client certificates.

Using custom authentication with X.509 certificates can be helpful if you've already authenticated your devices using X.509 certificates and want to perform additional validation and custom authorization. For example, if you store your devices' data such as their serial numbers in the X.509 client certificate, after AWS IoT Core authenticated the X.509 client certificate, you can use a custom authorizer to identify specific devices based on the information stored in the certificate's CommonName field. Using custom authentication with X.509 certificates can enhance your device security management when connecting devices to AWS IoT Core and provides more flexibility to manage the authentication and authorization logic. AWS IoT Core supports custom authentication with X.509 certificates using the X.509 certificate and custom authorizer authentication type, which works with both the [MQTT](https://docs.aws.amazon.com//iot/latest/developerguide/mqtt.html) protocol and the [HTTPS](https://docs.aws.amazon.com//iot/latest/developerguide/http.html) protocol. For more information about the authentication types and application protocols that AWS IoT Core device endpoints support, see [Device communication protocols](https://docs.aws.amazon.com//iot/latest/developerguide/protocols.html).

**Note**  
Custom authentication with X.509 client certificates is not supported in the AWS GovCloud (US) Regions.

**Important**  
You must use an endpoint created using [domain configurations](iot-custom-endpoints-configurable.md). In addition, clients must provide the [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) extension when connecting to AWS IoT Core.

**Topics**
+ [Step 1: Register your X.509 client certificates with AWS IoT Core](#custom-auth-509cert-client)
+ [Step 2: Create a Lambda function](#custom-auth-509cert-lambda)
+ [Step 3: Create a custom authorizer](#custom-auth-509cert-authorizer)
+ [Step 4: Set authentication type and application protocol in a domain configuration](#custom-auth-509cert-domainconfig)

## Step 1: Register your X.509 client certificates with AWS IoT Core
<a name="custom-auth-509cert-client"></a>

If you haven't done this already, register and activate your [X.509 client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/x509-client-certs.html) with AWS IoT Core. Otherwise, skip to the next step.

To register and activate your client certificates with AWS IoT Core, follow the steps:

1. If you [create client certificates directly with AWS IoT](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-create.html). These client certificates will be automatically registered with AWS IoT Core.

1. If you [create your own client certificates](https://docs.aws.amazon.com//iot/latest/developerguide/device-certs-your-own.html), follow [these instructions to register them with AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/register-device-cert.html).

1. To activate your client certificates, follow [these instructions](https://docs.aws.amazon.com//iot/latest/developerguide/activate-or-deactivate-device-cert.html).

## Step 2: Create a Lambda function
<a name="custom-auth-509cert-lambda"></a>

AWS IoT Core uses custom authorizers to implement custom authentication and authorization schemes. A custom authorizer is associated with a Lambda function that determines whether a device is authenticated and what operations the device is allowed to perform. When a device connects to AWS IoT Core, AWS IoT Core retrieves the authorizer details including authorizer name and associated Lambda function, and invokes the Lambda function. The Lambda function receives an event that contains a JSON object with the device's X.509 client certificate data. Your Lambda function uses this event JSON object to evaluate the authentication request, decide the actions to take, and send a response back.

### Lambda function event example
<a name="custom-auth-509cert-event"></a>

The following example JSON object contains all possible fields that can be included. The actual JSON object will only contain fields relevant to the specific connection request.

```
{
	"token": "aToken",
	"signatureVerified": true,
	"protocols": [
		"tls",
		"mqtt"
	],
	"protocolData": {
		"tls": {
			"serverName": "serverName",
			"x509CertificatePem": "x509CertificatePem",
			"principalId": "principalId"
		},
		"mqtt": {
			"clientId": "myClientId",
                     "username": "myUserName",
                     "password": "myPassword"
		}
	},
	"connectionMetadata": {
		"id": "UUID"
	}
}
```

`signatureVerified`  
A Boolean value that indicates whether the token signature configured in the authorizer is verified or not before invoking the authorizer's Lambda function. If the authorizer is configured to disable token signing, this field will be false. 

`protocols`  
An array that contains the protocols to expect for the request.

`protocolData`  
An object that contains information of the protocols used in the connection. It provides protocol-specific details that can be useful for authentication, authorization, and more.  
`tls` - This object holds information related to the TLS (Transport Layer Security) protocol.   
+ `serverName` - The [Server Name Indication (SNI)](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) hostname string. AWS IoT Core requires devices to send the [SNI extension](https://www.rfc-editor.org/rfc/rfc3546#section-3.1) to the Transport Layer Security (TLS) protocol and provide the complete endpoint address in the `host_name` field.
+ `x509CertificatePem` - The X.509 certificate in PEM format, which is used for client authentication in the TLS connection.
+ `principalId` - The principal identifier associated with the client in the TLS connection.
`mqtt` - This object holds information related to the MQTT protocol.  
+ `clientId` - A string only needs to be included in the event that the device sends this value.
+ `username` - The user name provided in the MQTT Connect packet.
+ `password` - The password provided in the MQTT Connect packet.

`connectionMetadata`  
Metadata of the connection.  
`id` - The connection ID, which you can use for logging and troubleshooting.

**Note**  
In this event JSON object, `x509CertificatePem` and `principalId` are two new fields in the request. The value of `principalId` is the same as the value of `certificateId`. For more information, see [Certificate](https://docs.aws.amazon.com//iot/latest/apireference/API_Certificate.html).

### Lambda function response example
<a name="custom-auth-509cert-response"></a>

The Lambda function should use information from the event JSON object to authenticate the incoming connection and decide what actions are permitted in the connection.

The following JSON object contains an example response that your Lambda function can send.

```
{
	"isAuthenticated": true,
	"principalId": "xxxxxxxx",
	"disconnectAfterInSeconds": 86400,
	"refreshAfterInSeconds": 300,
	"policyDocuments": [
		{
			"Version": "2012-10-17",		 	 	 
			"Statement": [
				{
					"Effect": "Allow",
					"Action": "iot:Publish",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topic/customauthtesting"
				}
			]
		}
	]
}
```

In this example, this function should send a response that contains the following values.

`isAuthenticated`  
A Boolean value that indicates whether the request is authenticated.

`principalId`  
An alphanumeric string that acts as an identifier for the token sent by the custom authorization request. The value must be an alphanumeric string with at least one, and no more than 128, characters. It identifies the connection in logs. The value of `principalId` must be the same as the value of `principalId` in the event JSON object (i.e. certificateId of the X.509 certificate).

`policyDocuments`  
A list of JSON-formatted AWS IoT Core policy documents. The value is optional and supports [thing policy variables](https://docs.aws.amazon.com//iot/latest/developerguide/thing-policy-variables.html) and [certificate policy variables](https://docs.aws.amazon.com//iot/latest/developerguide/cert-policy-variables.html). The maximum number of policy documents is 10. Each policy document can contain a maximum of 2,048 characters. If you have multiple policies attached to your client certificate and the Lambda function, the permission is a collection of all policies. For more information about creating AWS IoT Core policies, see [Policies](https://docs.aws.amazon.com//iot/latest/developerguide/iot-policies.html).

`disconnectAfterInSeconds`  
An integer that specifies the maximum duration (in seconds) of the connection to the AWS IoT Core gateway. The minimum value is 300 seconds, and the maximum value is 86,400 seconds. `disconnectAfterInSeconds` is for the lifetime of a connection and doesn't get refreshed on consecutive policy refreshes.

`refreshAfterInSeconds`  
An integer that specifies the interval between policy refreshes. When this interval passes, AWS IoT Core invokes the Lambda function to allow for policy refreshes. The minimum value is 300 seconds, and the maximum value is 86,400 seconds.

### Example Lambda function
<a name="custom-auth-509cert-js-example"></a>

The following is a sample Node.js Lambda function. The function examines the client's X.509 certificate and extracts relevant information such as the serial number, fingerprint, and subject name. If the extracted information matches the expected values, the client is granted access to connect. This mechanism ensures that only authorized clients with valid certificates can establish a connection.

```
const crypto = require('crypto');

exports.handler = async (event) => {
    
    // Extract the certificate PEM from the event
    const certPem = event.protocolData.tls.x509CertificatePem;
    
    // Parse the certificate using Node's crypto module
    const cert = new crypto.X509Certificate(certPem);
    
    var effect = "Deny";
    // Allow permissions only for a particular certificate serial, fingerprint, and subject
    if (cert.serialNumber === "7F8D2E4B9C1A5036DE8F7C4B2A91E5D80463BC9A1257" // This is a random serial
       && cert.fingerprint === "F2:9A:C4:1D:B5:E7:08:3F:6B:D0:4E:92:A7:C1:5B:8D:16:0F:E3:7A" // This is a random fingerprint
       && cert.subject === "allow.example.com") {
      effect = "Allow";
    }
    
    return generateAuthResponse(event.protocolData.tls.principalId, effect);
};


// Helper function to generate the authorization response.
function generateAuthResponse(principalId, effect) {
    const authResponse = {
        isAuthenticated: true,
        principalId,
        disconnectAfterInSeconds: 3600,
        refreshAfterInSeconds: 300,
        policyDocuments: [
          {
            Version: "2012-10-17",		 	 	 
            Statement: [
              {
                Action: ["iot:Connect"],
                Effect: effect,
                Resource: [
                  "arn:aws:iot:us-east-1:123456789012:client/myClientName"
                ]
              },
              {
                Action: ["iot:Publish"],
                Effect: effect,
                Resource: [
                  "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
                ]
              },
              {
                Action: ["iot:Subscribe"],
                Effect: effect,
                Resource: [
                   "arn:aws:iot:us-east-1:123456789012:topicfilter/telemetry/myClientName"
                ]
              },
              {
                Action: ["iot:Receive"],
                Effect: effect,
                Resource: [
                   "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
                ]
              }
            ]
          }
        ]
      };

  return authResponse;
}
```

The preceding Lambda function returns the following JSON when it receives a certificate with the expected serial, fingerprint, and subject. The value of `x509CertificatePem` will be the client certificate provided in the TLS handshake. For more information, see [Defining your Lambda function](https://docs.aws.amazon.com//iot/latest/developerguide/config-custom-auth.html#custom-auth-lambda).

```
{
	"isAuthenticated": true,
	"principalId": "principalId in the event JSON object",
	"policyDocuments": [
		{
			"Version": "2012-10-17",		 	 	 
			"Statement": [
				{
					"Action": "iot:Connect",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:client/myClientName"
				},
				{
					"Action": "iot:Publish",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
				},
				{
					"Action": "iot:Subscribe",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/telemetry/myClientName"
				},
				{
					"Action": "iot:Receive",
					"Effect": "Allow",
					"Resource": "arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"
				}
			]
		}
	],
	"disconnectAfterInSeconds": 3600,
	"refreshAfterInSeconds": 300
}
```

## Step 3: Create a custom authorizer
<a name="custom-auth-509cert-authorizer"></a>

After [you define the Lambda function](#custom-auth-509cert-lambda), create a custom authorizer to manage your own client authentication and authorization logic. You can follow the detailed instructions in [Step 3: Create a customer authorizer resource and its authorization](https://docs.aws.amazon.com//iot/latest/developerguide/custom-auth-tutorial.html#custom-auth-tutorial-authorizer). For more information, see [Creating an authorizer](https://docs.aws.amazon.com//iot/latest/developerguide/config-custom-auth.html). 

In the process of creating the custom authorizer, you must grant AWS IoT permission to invoke the Lambda function after it's created. For detailed instructions, see [Authorizing AWS IoT to invoke your Lambda function](custom-auth-authorize.md).

## Step 4: Set authentication type and application protocol in a domain configuration
<a name="custom-auth-509cert-domainconfig"></a>

To authenticate devices using custom authentication with X.509 client certificates, you must set the authentication type and application protocol in a domain configuration, and you must send the SNI extension. The value of `authenticationType` must be `CUSTOM_AUTH_X509`, and the value of `applicationProtocol` can either be `SECURE_MQTT` or `HTTPS`.

### Set authentication type and application protocol in domain configuration (CLI)
<a name="custom-auth-509cert-cli"></a>

If you don't have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/create-domain-configuration.html) command to create one. The value of `authenticationType` must be `CUSTOM_AUTH_X509`, and the value of `applicationProtocol` can either be `SECURE_MQTT` or `HTTPS`.

```
aws iot create-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type CUSTOM_AUTH_X509 \  
    --application-protocol SECURE_MQTT \ 
    --authorizer-config '{
        "defaultAuthorizerName": my-custom-authorizer
    }'
```

If you already have a domain configuration, use the [https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html](https://docs.aws.amazon.com//cli/latest/reference/iot/update-domain-configuration.html) command update `authenticationType` and `applicationProtocol` if needed. Note that you can't change the authentication type or protocol on the default endpoint (`iot:Data-ATS`).

```
aws iot update-domain-configuration \
    --domain-configuration-name domainConfigurationName \
    --authentication-type CUSTOM_AUTH_X509 \  
    --application-protocol SECURE_MQTT \
    --authorizer-config '{
        "defaultAuthorizerName": my-custom-authorizer
    }'
```

`domain-configuration-name`  
The name of the domain configuration.

`authentication-type`  
The authentication type of the domain configuration. For more information, see [choosing an authentication type](protocols.md#connection-protocol-auth-mode).

`application-protocol`  
The application protocol which devices use to communicate with AWS IoT Core. For more information, see [choosing an application protocol](protocols.md#protocol-selection).

`--authorizer-config`  
An object that specifies the authorizer configuration in a domain configuration.

`defaultAuthorizerName`  
The name of the authorizer for a domain configuration.

For more information, see [CreateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_CreateDomainConfiguration.html) and [UpdateDomainConfiguration](https://docs.aws.amazon.com//iot/latest/apireference/API_UpdateDomainConfiguration.html) from the *AWS IoT API Reference*. For more information about domain configuration, see [Domain configurations](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable.html).

# Connecting to AWS IoT Core by using custom authentication
<a name="custom-auth"></a>

 Devices can connect to AWS IoT Core by using custom authentication with any protocol that AWS IoT Core supports for device messaging. For more information about supported communication protocols, see [Device communication protocols](protocols.md).  The connection data that you pass to your authorizer Lambda function depends on the protocol you use. For more information about creating your authorizer Lambda function, see [Defining your Lambda function](custom-auth-lambda.md). The following sections explain how to connect to authenticate by using each supported protocol.

## HTTPS
<a name="custom-auth-http"></a>

Devices sending data to AWS IoT Core by using the [HTTP Publish API](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdata_Publish.html) can pass credentials either through request headers or query parameters in their HTTP POST requests. Devices can specify an authorizer to invoke by using the `x-amz-customauthorizer-name` header or query parameter. If you have token signing enabled in your authorizer, you must pass the `token-key-name` and `x-amz-customauthorizer-signature` in either request headers or query parameters. Note that the `token-signature` value must be URL-encoded when using JavaScript from within the browser.

**Note**  
The customer authorizer for the HTTPS protocol only supports publish operations. For more information about the HTTPS protocol, see [Device communication protocols](protocols.md).

The following example requests show how you pass these parameters in both request headers and query parameters. 

```
//Passing credentials via headers
POST /topics/topic?qos=qos HTTP/1.1
Host: your-endpoint 
x-amz-customauthorizer-signature: token-signature
token-key-name: token-value 
x-amz-customauthorizer-name: authorizer-name

//Passing credentials via query parameters
POST /topics/topic?qos=qos&x-amz-customauthorizer-signature=token-signature&token-key-name=token-value HTTP/1.1
```

## MQTT
<a name="custom-auth-mqtt"></a>

 Devices connecting to AWS IoT Core by using an MQTT connection can pass credentials through the `username` and `password` fields of MQTT messages. The `username` value can also optionally contain a query string that passes additional values (including a token, signature, and authorizer name) to your authorizer. You can use this query string if you want to use a token-based authentication scheme instead of `username` and `password` values.  

**Note**  
 Data in the password field is base64-encoded by AWS IoT Core. Your Lambda function must decode it. 

 The following example contains a `username` string that contains extra parameters that specify a token and signature.  

```
username?x-amz-customauthorizer-name=authorizer-name&x-amz-customauthorizer-signature=token-signature&token-key-name=token-value
```

To invoke an authorizer, devices connecting to AWS IoT Core by using MQTT and custom authentication must connect on port 443. They also must pass the Application Layer Protocol Negotiation (ALPN) TLS extension with a value of `mqtt` and the Server Name Indication (SNI) extension with the host name of their AWS IoT Core data endpoint. To avoid potential errors, the value for `x-amz-customauthorizer-signature` should be URL encoded. We also highly recommend that the values of `x-amz-customauthorizer-name` and `token-key-name` be URL encoded. For more information about these values, see [Device communication protocols](protocols.md). The V2 [AWS IoT Device SDKs, Mobile SDKs, and AWS IoT Device Client](iot-sdks.md) can configure both of these extensions. 

## MQTT over WebSockets
<a name="custom-auth-websockets"></a>

 Devices connecting to AWS IoT Core by using MQTT over WebSockets can pass credentials in one of the two following ways. 
+ Through request headers or query parameters in the HTTP UPGRADE request to establish the WebSockets connection.
+ Through the `username` and `password` fields in the MQTT CONNECT message.

 If you pass credentials through the MQTT connect message, the ALPN and SNI TLS extensions are required. For more information about these extensions, see [MQTT](#custom-auth-mqtt).   The following example demonstrates how to pass credentials through the HTTP Upgrade request. 

```
GET /mqtt HTTP/1.1
Host: your-endpoint 
Upgrade: WebSocket 
Connection: Upgrade 
x-amz-customauthorizer-signature: token-signature
token-key-name: token-value 
sec-WebSocket-Key: any random base64 value 
sec-websocket-protocol: mqtt 
sec-WebSocket-Version: websocket version
```

## Signing the token
<a name="custom-auth-token-signature"></a>

You must sign the token with the private key of the public-private key pair that you used in the `create-authorizer` call. The following examples show how to create the token signature by using a UNIX-like command and JavaScript. They use the SHA-256 hash algorithm to encode the signature.

------
#### [ Command line ]

```
echo -n TOKEN_VALUE | openssl dgst -sha256 -sign PEM encoded RSA private key | openssl base64
```

------
#### [ JavaScript ]

```
const crypto = require('crypto')

const key = "PEM encoded RSA private key"

const k = crypto.createPrivateKey(key)
let sign = crypto.createSign('SHA256')
sign.write(t)
sign.end()
const s = sign.sign(k, 'base64')
```

------

# Troubleshooting your authorizers
<a name="custom-auth-troubleshooting"></a>

 This topic walks through common issues that can cause problems in custom authentication workflows and steps for resolving them. To troubleshoot issues most effectively, enable CloudWatch logs for AWS IoT Core and set the log level to **DEBUG**. You can enable CloudWatch logs in the AWS IoT Core console ([https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/)). For more information about enabling and configuring logs for AWS IoT Core, see [Configure AWS IoT logging](configure-logging.md). 

**Note**  
If you leave the log level at **DEBUG** for long periods of time, CloudWatch might store large amounts of logging data. This can increase your CloudWatch charges. Consider using resource-based logging to increase the verbosity for only devices in a particular thing group. For more information about resource-based logging, see [Configure AWS IoT logging](configure-logging.md). Also, when you're done troubleshooting, reduce the log level to a less verbose level.

Before you start troubleshooting, review [Understanding the custom authentication workflow](custom-authorizer.md) for a high-level view of the custom authentication process. This helps you understand where to look for the source of a problem.

This topic discusses the following two areas for you to investigate.
+ Issues related to your authorizer's Lambda function.
+ Issues related to your device.

## Check for issues in your authorizer’s Lambda function
<a name="custom-auth-troubleshooting-lambda"></a>

Perform the following steps to make sure that your devices’ connection attempts are invoking your Lambda function.

1. Verify which Lambda function is associated with your authorizer.

   You can do this by calling the [DescribeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuthorizer.html) API or by clicking on the desired authorizer in the **Secure** section of the AWS IoT Core console.

1. Check the invocation metrics for the Lambda function. Perform the following steps to do this.

   1. Open the AWS Lambda console ([https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)) and select the function that is associated with your authorizer.

   1. Choose the **Monitor** tab and view metrics for the time frame that is relevant to your problem.

1. If you see no invocations, verify that AWS IoT Core has permission to invoke your Lambda function. If you see invocations, skip to the next step. Perform the following steps to verify that your Lambda function has the required permissions.

   1. Choose the **Permissions** tab for your function in the AWS Lambda console.

   1. Find the **Resource-based Policy** section at the bottom of the page. If your Lambda function has the required permissions, the policy looks like the following example.  
****  

      ```
      {
        "Version":"2012-10-17",		 	 	 
        "Id": "default",
        "Statement": [
          {
            "Sid": "Id123",
            "Effect": "Allow",
            "Principal": {
              "Service": "iot.amazonaws.com"
            },
            "Action": "lambda:InvokeFunction",
            "Resource": "arn:aws:lambda:us-east-1:111111111111:function:FunctionName",
            "Condition": {
              "ArnLike": {
                "AWS:SourceArn": "arn:aws:iot:us-east-1:111111111111:authorizer/AuthorizerName"
              },
              "StringEquals": {
                "AWS:SourceAccount": "111111111111"
              }
            }
          }
        ]
      }
      ```

   1. This policy grants the `InvokeFunction` permission on your function to the AWS IoT Core principal. If you don't see it, you'll have to add it by using the [AddPermission](https://docs.aws.amazon.com/lambda/latest/dg/API_AddPermission.html) API. The following example shows you how to do this by using the AWS CLI.

      ```
      aws lambda add-permission --function-name FunctionName --principal iot.amazonaws.com --source-arn AuthorizerARn --statement-id Id-123 --action "lambda:InvokeFunction"
      ```

1. If you see invocations, verify that there are no errors. An error might indicate that the Lambda function isn't properly handling the connection event that AWS IoT Core sends to it.

   For information about handling the event in your Lambda function, see [Defining your Lambda function](custom-auth-lambda.md). You can use the test feature in the AWS Lambda console ([https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)) to hard-code test values in the function to make sure that the function is handling events correctly.

1. If you see invocations with no errors, but your devices are not able to connect (or publish, subscribe, and receive messages), the issue might be that the policy that your Lambda function returns doesn't give permissions for the actions that your devices are trying to take. Perform the following steps to determine whether anything is wrong with the policy that the function returns.

   1. Use an Amazon CloudWatch Logs Insights query to scan logs over a short period of time to check for failures. The following example query sorts events by timestamp and looks for failures.

      ```
      display clientId, eventType, status, @timestamp | sort @timestamp desc | filter status = "Failure"    
      ```

   1. Update your Lambda function to log the data that it's returning to AWS IoT Core and the event that triggers the function. You can use these logs to inspect the policy that the function creates.

1. If you see invocations with no errors, but your devices are not able to connect (or publish, subscribe, and receive messages), another reason can be that your Lambda function exceeds the timeout limit. The Lambda function timeout limit for custom authorizer is 5 seconds. You can check the function duration in CloudWatch logs or metrics. 

## Investigating device issues
<a name="custom-auth-troubleshooting-investigate"></a>

If you find no issues with invoking your Lambda function or with the policy that the function returns, look for problems with your devices' connection attempts. Malformed connection requests can cause AWS IoT Core not to trigger your authorizer. Connection problems can occur at both the TLS and application layers.

**Possible TLS layer issues:**
+ Customers must pass either a hostname header (HTTP, MQTT over WebSockets) or the Server Name Indication TLS extension (HTTP, MQTT over WebSockets, MQTT) in all custom authentication requests. In both cases, the value passed must match one of your account’s AWS IoT Core data endpoints. These are the endpoints that are returned when you perform the following CLI commands.
  + `aws iot describe-endpoint --endpoint-type iot:Data-ATS`
  + `aws iot describe-endpoint --endpoint-type iot:Data` (for legacy VeriSign endpoints)
+ Devices that use custom authentication for MQTT connections must also pass the Application Layer Protocol Negotiation (ALPN) TLS extension with a value of `mqtt`.
+ Custom authentication is currently available only on port 443.

**Possible application layer issues:**
+ If signing is enabled (the `signingDisabled` field is false in your authorizer), look for the following signature issues.
  + Make sure that you're passing the token signature in either the `x-amz-customauthorizer-signature`header or in a query string parameter.
  + Make sure that the service isn't signing a value other than the token.
  + Make sure that you pass the token in the header or query parameter that you specified in the `token-key-name` field in your authorizer.
+ Make sure that the authorizer name you pass in the `x-amz-customauthorizer-name` header or query string parameter is valid or that you have a default authorizer defined for your account.