# Authenticating Using the Salesforce Mobile SDK

These instructions describe how to authenticate the Service Chat SDK using the provided authentication mechanism within the Salesforce Mobile SDK.

## Before You Begin

:::important
The legacy chat product is scheduled for retirement on February 14, 2026, and is in maintenance mode until then. During this phase, you can continue to use chat, but we no longer recommend that you implement new chat channels. To avoid service interruptions to your customers, migrate to [Messaging for In-App and Web](https://help.salesforce.com/s/articleView?id=service.miaw_intro_landing.htm\&type=5) before that date. Messaging offers many of the [chat features](https://help.salesforce.com/s/articleView?id=service.miaw_chat_vs_messaging.htm\&type=5) that you love plus asynchronous conversations that can be picked back up at any time. Learn about chat retirement in [Help](https://help.salesforce.com/s/articleView?id=001790618\&type=1).
:::

Before starting, make sure that you’ve already:

- Installed the Service Chat SDK. See [Install the Service SDK for Android](/docs/service/service-sdk-android/guide/android-install-sdk.md).
- Installed the [Salesforce Mobile SDK](https://github.com/forcedotcom/SalesforceMobileSDK-Android). If you want to install this SDK using maven, add a dependency on `com.salesforce.mobilesdk:SalesforceSDK:<VERSION_NUMBER>` to your module's `build.gradle` file.
- Created a connected app that allows the SDK to authenticate with your Salesforce Experience Cloud site. See [Connected Apps](https://help.salesforce.com/articleView?id=connected_app_overview.htm). For an overview of Salesforce authentication from a mobile device, see [Understand Security and Authentication](https://trailhead.salesforce.com/en/modules/mobile_sdk_introduction/units/mobilesdk_intro_security).

:::note
When creating a connected app, be sure that it has access to the `chatter_api` scope. See [Scope Parameter Values](https://help.salesforce.com/articleView?id=remoteaccess_oauth_scopes.htm).
:::

1. If you're using a Salesforce Experience Cloud site, be sure to configure the login endpoint as described in the Salesforce Mobile SDK documentation ([Configure the Login Endpoint](https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/communities_login_endpoint.htm)).

   The documentation describes how to use the first server listed in your `servers.xml` file as the default login location. For example:

   ```xml
   <servers>
     <server name="Site Login" url="https://MY_SITE_URL.com"/>
   </servers>
   ```

2. Add an `account_type` property to `strings.xml`. The property must be unique to your app to prevent conflicts with other apps that use the Service Chat SDK or the Salesforce Mobile SDK.

   ```xml
   <string name="account_type">com.mycompany.myapp</string>
   ```

3. Implement [`AuthenticatedUser`](https://forcedotcom.github.io/ServiceSDK-Android/releases/common/8.0.5/api/reference/com/salesforce/android/service/common/http/AuthenticatedUser.html) as a wrapper to your Mobile SDK user.

   In Java:

   ```java
   import com.salesforce.androidsdk.accounts.UserAccount;
   import com.salesforce.android.service.common.http.AuthenticatedUser;

   public class MobileSdkUser implements AuthenticatedUser {
     private final String mUserId;

     public MobileSdkUser (UserAccount userAccount) {
       mUserId = userAccount.getUserId();
     }

     @Override public String getUserId () {
       return mUserId;
     }
   }
   ```

   In Kotlin:

   ```java
   class MobileSdkUser(userAccount: UserAccount) : AuthenticatedUser {
     private val mUserId: String

     init {
       mUserId = userAccount.getUserId()
     }

     override fun getUserId(): String {
       return mUserId
     }
   }
   ```

   :::note
   `AuthenticatedUser.getUserId` must return the Salesforce user ID (`UserAccount.getUserId`) for the Case Management message feed to display correctly.
   :::

4. Implement [`AuthTokenProvider`](https://forcedotcom.github.io/ServiceSDK-Android/releases/common/8.0.5/api/reference/com/salesforce/android/service/common/http/AuthTokenProvider.html) as a wrapper to your Mobile SDK authentication system.

   In Java:

   ```java
   import android.support.annotation.NonNull;
   import android.support.annotation.Nullable;
   import com.salesforce.android.service.common.http.AuthTokenProvider;
   import com.salesforce.android.service.common.http.ResponseSummary;
   import com.salesforce.androidsdk.rest.ClientManager;

   public class MobileSdkAuthTokenProvider implements AuthTokenProvider {

     private final ClientManager.AccMgrAuthTokenProvider mTokenProvider;
     private String mAuthToken;

     public MobileSdkAuthTokenProvider (ClientManager.AccMgrAuthTokenProvider tokenProvider,
                                        String initialToken) {
       mTokenProvider = tokenProvider;
       mAuthToken = initialToken;
     }

     @Nullable @Override public String getToken () {
       return mAuthToken;
     }

     @Nullable @Override public String getTokenType () {
       return "Bearer";
     }

     @Override public boolean canRefresh () {
       return true;
     }

     @Override public void refreshToken (@NonNull ResponseSummary responseSummary) {
       mAuthToken = mTokenProvider.getNewAuthToken();
     }
   }
   ```

   In Kotlin:

   ```java
   class MobileSdkAuthTokenProvider(
     private val mTokenProvider: ClientManager.AccMgrAuthTokenProvider,
     private var mAuthToken: String?) : AuthTokenProvider {

     override fun getToken(): String? {
       return mAuthToken
     }

     override fun getTokenType(): String? {
       return "Bearer"
     }

     override fun canRefresh(): Boolean {
       return true
     }

     override fun refreshToken(responseSummary: ResponseSummary) {
       mAuthToken = mTokenProvider.getNewAuthToken()
     }
   }
   ```

5. When your app launches, initialize the Salesforce Mobile SDK.

   ```java
   // Initialize the Salesforce Mobile SDK
   SalesforceSDKManager.initNative(context, null, MainActivity.class);
   ```

   For more information, see the [SalesforceSDKManager documentation](https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/android_native_classes_salesforcesdkmanager.htm) in the Mobile SDK Developer’s Guide.

6. Write code that allows a user to log in and log out of their org using the Salesforce Mobile SDK. Make sure the user logs in before showing the Service Chat SDK UI.

   For example:

   ```java
   public void login (final Activity activity) {
     SalesforceSDKManager.getInstance()
                         .getClientManager()
                         .getRestClient(activity,
                                        new ClientManager.RestClientCallback() {

       @Override public void authenticatedRestClient (RestClient client) {
         // Handle authenticated state activity here
       }
     });
   }

   public void logout (final Activity activity) {
     SalesforceSDKManager.getInstance().logout(activity, true);
   }
   ```

7. When configuring Knowledge (using [`KnowledgeConfiguration`](https://forcedotcom.github.io/ServiceSDK-Android/releases/knowledge/4.3.6/api/reference/com/salesforce/android/knowledge/core/KnowledgeConfiguration.html)) or Case Management (using [`CaseConfiguration`](https://forcedotcom.github.io/ServiceSDK-Android/releases/case/4.2.7/api/reference/com/salesforce/android/cases/core/CaseConfiguration.html)), use the `withAuthConfig` method in the builder and pass in your implementation for [`AuthenticatedUser`](https://forcedotcom.github.io/ServiceSDK-Android/releases/common/8.0.5/api/reference/com/salesforce/android/service/common/http/AuthenticatedUser.html) and [`AuthTokenProvider`](https://forcedotcom.github.io/ServiceSDK-Android/releases/common/8.0.5/api/reference/com/salesforce/android/service/common/http/AuthTokenProvider.html).

   This code sample illustrates how it works with Knowledge:

   ```java
   // Create Knowledge configuration builder
   KnowledgeConfiguration.Builder builder =
     KnowledgeConfiguration.builder(siteUrl).offlineResourceConfig(offlineConfig);

   // Grab a user account from the Salesforce Mobile SDK
   UserAccount userAccount =
     SalesforceSDKManager.getInstance().getUserAccountManager().getCurrentUser();

   if (userAccount != null) {

     // Create an authorization token provider from the Salesforce Mobile SDK
     ClientManager.AccMgrAuthTokenProvider authTokenProvider =
       new ClientManager.AccMgrAuthTokenProvider(
         SalesforceSDKManager.getInstance().getClientManager(),
         userAccount.getInstanceServer(),
         userAccount.getAuthToken(),
         userAccount.getRefreshToken());

     // Create a wrapper with the Salesforce Mobile SDK token provider
     AuthTokenProvider provider =
       new MobileSdkAuthTokenProvider(authTokenProvider,
         userAccount.getAuthToken());

     // Build a config using the token provider and the authenticated user
     builder.withAuthConfig(provider, new MobileSdkUser(userAccount));
   }

   // And now build a configuration object!
   KnowledgeConfiguration config = builder.build();
   ```

   This code sample illustrates how it works with Case Management:

   ```java
   // Create Case Management configuration builder
   CaseConfiguration.Builder builder =
     new CaseConfiguration.Builder(SITE_URL, CREATE_CASE_ACTION_NAME)

   // Grab a user account from the Salesforce Mobile SDK
   UserAccount userAccount =
     SalesforceSDKManager.getInstance().getUserAccountManager().getCurrentUser();

   if (userAccount != null) {

     // Create an authorization token provider from the Salesforce Mobile SDK
     ClientManager.AccMgrAuthTokenProvider authTokenProvider =
       new ClientManager.AccMgrAuthTokenProvider(
         SalesforceSDKManager.getInstance().getClientManager(),
         userAccount.getInstanceServer(),
         userAccount.getAuthToken(),
         userAccount.getRefreshToken());

     // Create a wrapper with the Salesforce Mobile SDK token provider
     AuthTokenProvider provider =
       new MobileSdkAuthTokenProvider(authTokenProvider,
         userAccount.getAuthToken());

     // Build a config using the token provider and the authenticated user
     builder.withAuthConfiguration(provider, new MobileSdkUser(userAccount))
            .caseListName(CASE_LIST_NAME);
   }

   // Create a core configuration instance
   CaseConfiguration coreConfiguration = builder.build();
   ```

At this point, you can use the features of the Service Chat SDK as an authenticated user.
