> ## Documentation Index
> Fetch the complete documentation index at: https://moengage.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# JWT Authentication

> Secure your MoEngage data collection by implementing JWT authentication in your Android app.

## Overview

JWT (JSON Web Token) authentication is a standard method for securely verifying user identity. By implementing JWT authentication, you add a critical layer of security to your data collection process with MoEngage.

The feature ensures that the data sent on behalf of your identified users is authentic and is not tampered with. This security is achieved by requiring a token that is cryptographically signed by your own server, which prevents unauthorized users from impersonating your legitimate users.

<Check>
  Before you begin the implementation, ensure you meet the following requirements:

  * Your application must use the MoEngage Android SDK version **14.04.00** or higher to access the JWT authentication feature.
  * You must have access to your MoEngage dashboard to manage public keys and configure the feature's enforcement settings.
</Check>

The following diagram illustrates the interaction between your application, your server, the MoEngage SDK, and the MoEngage server:

<img src="https://mintcdn.com/moengage/Jtvf10ggM77HdKvB/images/nextttt(1).jpeg?fit=max&auto=format&n=Jtvf10ggM77HdKvB&q=85&s=c9c81f1b45cf152e3109ada2c2538739" alt="Nextttt(1)" width="1399" height="706" data-path="images/nextttt(1).jpeg" />

## Integration

Perform the following to integrate JWT authentication into your Android application:

### Step 1: Enable JWT Authentication

You can enable JWT authentication during [SDK initialization](https://www.moengage.com/docs/developer-guide/android-sdk/sdk-integration/basic-integration/sdk-initialization) by configuring the ***NetworkAuthorizationConfig*** property on the ***MoEngage.Builder*** object.

<CodeGroup>
  ```kotlin Kotlin wrap theme={null}
  val moEngage = MoEngage.Builder(
          application = application,
          appId = "YOUR_WORKSPACE_ID",
          dataCenter = DataCenter.DATA_CENTER_X
      )
      .configureNetworkRequest(NetworkRequestConfig(NetworkAuthorizationConfig(isJwtEnabled = true)))
      .build()
  MoEngage.initialiseDefaultInstance(moEngage)
  ```

  ```java Java theme={null}
  MoEngage moEngage = new MoEngage.Builder(application, "YOUR_WORKSPACE_ID", DataCenter.DATA_CENTER_X)
      .configureNetworkRequest(new NetworkRequestConfig(new NetworkAuthorizationConfig(true)))
      .build();
  MoEngage.initialiseDefaultInstance(moEngage);
  ```
</CodeGroup>

### Step 2: Pass the JWT to the SDK

Your application is responsible for managing the JWT lifecycle. The recommended flow is to fetch a token upon user login and pass the token to the SDK. You should also check if the token has expired on subsequent app launches and fetch a new one if necessary. 

Use the [***MoECoreHelper.passAuthenticationDetails()***](https://moengage.github.io/android-api-reference/core/com.moengage.core/-mo-e-core-helper/pass-authentication-details.html) to provide the token to the SDK.

<CodeGroup>
  ```kotlin Kotlin wrap theme={null}
  val data = AuthenticationData.Jwt("YOUR_JWT_TOKEN", "USER_IDENTIFIER")
  MoECoreHelper.passAuthenticationDetails(context, data)
  ```

  ```java Java theme={null}
  AuthenticationData data = new AuthenticationData.Jwt("YOUR_JWT_TOKEN", "USER_IDENTIFIER");
  MoECoreHelper.INSTANCE.passAuthenticationDetails(application.getApplicationContext(), data);
  ```
</CodeGroup>

### Step 3: Handle Authentication Errors

To handle token validation errors that the MoEngage server returns, register an [***OnAuthenticationError***](https://moengage.github.io/android-api-reference/core/com.moengage.core.model.authentication/-on-authentication-error/index.html) listener. The SDK invokes this listener when an authentication error occurs, which allows your application to fetch and provide a new token. Register the listener in a global scope, such as the `onCreate()` of your `Application` class, to ensure your application always receives callbacks.

<CodeGroup>
  ```kotlin Kotlin wrap theme={null}
  val authErrorListener = OnAuthenticationError { error ->
    when (error.data) {
      is ErrorData.Jwt -> {
         // Handle JWT authentication error
         val errorData = error.data as ErrorData.Jwt
         val jwtError = errorData.code
         val message = errorData.message
         // Take appropriate action based on the jwtError
      }
    }
  }
  MoECoreHelper.registerAuthenticationListener(authErrorListener)
  ```

  ```java Java theme={null}
  OnAuthenticationError errorListener = new OnAuthenticationError() {
    @Override
    public void onError(@NonNull AuthenticationError error) {
        switch (error.getType()) {
            case JWT:
                ErrorData.Jwt jwtError = (ErrorData.Jwt) error.getData();
                // Handle JWT error
                JwtError jwtErrorType = jwtError.getCode();
                String message = jwtError.getMessage();
                // Take action based on jwtErrorType
                break;
        }
    }
  };
  MoECoreHelper.INSTANCE.registerAuthenticationListener(errorListener);
  ```
</CodeGroup>

<Info>
  * If an API request fails due to an authentication error, the SDK will not retry the request until your application provides a new token.
  * After 10 consecutive authentication failures in a single session, the SDK will stop attempting to sync data until the next session begins. This counter resets after any successful sync.
  * Upon user logout, if a data sync fails due to a JWT error, the pending data will be deleted, and no retry will be attempted.
</Info>
