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

# User Token Management

> Learn how to manage user authentication tokens and credentials in social.plus SDK

Use `AmityUserTokenManager` or the TypeScript `createUserToken(...)` helper to create user credentials for flows that require a user access token. This includes access to some beta features and server-side API workflows.

<Warning>
  The generated access token is not used by normal client SDK login. Create and consume these tokens only from a backend, tool, or trusted workflow where the token is not exposed to end users.
</Warning>

## Parameters

| Parameter                   | Required | Platforms                         | Description                                                                                                     |
| --------------------------- | -------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `apiKey`                    | Yes      | TypeScript, iOS, Android, Flutter | API key used to create the token manager or token request. Keep it in a trusted runtime when generating tokens. |
| `region` / `endpoint`       | Yes      | TypeScript, iOS, Android, Flutter | Region or endpoint used to route the token request.                                                             |
| `userId`                    | Yes      | TypeScript, iOS, Android, Flutter | Unique identifier of the user whose credentials are created.                                                    |
| `displayName`               | No       | TypeScript, iOS, Android, Flutter | Display name associated with the user credentials when provided.                                                |
| `authToken` / `secureToken` | No       | TypeScript, iOS, Android, Flutter | Secure authentication token used when your app enables secure mode.                                             |

## Create a user token

To create a user token, pass the user's identifier and optional secure-mode credentials from a trusted workflow.

Create the token with the SDK surface for your platform.

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { API_REGIONS, createUserToken } from '@amityco/ts-sdk';

  const { accessToken } = await createUserToken('your-api-key', API_REGIONS.SG, {
    userId: 'user_123',
    displayName: 'Jane Doe',
    authToken: 'secure-token',
  });

  console.log(accessToken);
  ```

  ```swift iOS theme={null}
  // 1. create AmityUserTokenManager instance.
  let userTokenManager = AmityUserTokenManager(apiKey: "<api-key>", region: .SG)

  func createNewUserTokenExample() async {
      // 2. call `createUserToken` on AmityUserTokenManager.
      do {
          let auth = try await userTokenManager.createUserToken(
              userId: "<user-id>",
              displayName: "<(optional)-display-name>",
              authToken: "<(optional)-auth-token>"
          )
          print("auth.accessToken: \(auth.accessToken)")
      } catch {
          print("unable to create a new user token: \(error.localizedDescription)")
      }
  }
  ```

  ```kotlin Android theme={null}
  fun createUserToken(
      userId: String,
      displayName: String,
      apiKey: String,
      endpoint: AmityEndpoint,
      authToken: String?
  ) {
      AmityUserTokenManager(
          apiKey = apiKey,
          endpoint = endpoint
      ).createUserToken(
          userId = userId,
          displayName = displayName,
          secureToken = authToken
      )
          .doOnSuccess { userToken : AmityUserToken ->
              // AmityUserToken
              val accessToken = userToken.accessToken
          }
          .doOnError {
              // Exception
          }
          .subscribe()
  }
  ```

  ```dart Flutter theme={null}
  void createUserToken(String userId, String displayname, String secureToken) {
    AmityUserTokenManager(
            apiKey: "your api key", endpoint: AmityRegionalHttpEndpoint.SG)
        //displayname and secureToken are optional
        .createUserToken(userId,
            displayname: displayname, secureToken: secureToken)
        .then((AmityUserToken token) {
            log("accessToken = ${token.accessToken}");
    });
  }
  ```
</CodeGroup>

## Token security

<AccordionGroup>
  <Accordion title="Secure storage">
    * Store tokens securely on the server side.
    * Use encryption for token storage.
    * Implement token rotation policies.
    * Never expose tokens in client-side code.
  </Accordion>

  <Accordion title="Network security">
    * Always use HTTPS for token transmission.
    * Implement proper authentication headers.
    * Use secure communication channels.
    * Log token usage for audit purposes.
  </Accordion>
</AccordionGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Token management">
    * Cache tokens to avoid unnecessary creation.
    * Implement token validation before usage.
    * Use connection pooling for better performance.
    * Handle token expiration gracefully.
  </Accordion>

  <Accordion title="Error handling">
    * Implement comprehensive error handling.
    * Log all token operations for debugging.
    * Provide meaningful error messages.
    * Implement retry logic for transient failures.
  </Accordion>

  <Accordion title="Performance">
    * Batch token operations when possible.
    * Use background processing for token creation.
    * Implement caching strategies.
    * Monitor token usage patterns.
  </Accordion>
</AccordionGroup>

## Related Topics

<CardGroup cols={2}>
  <Card title="User Authentication" href="../../../getting-started/authentication" icon="key">
    Learn about standard user login and authentication.
  </Card>

  <Card title="API Integration" href="/api-reference/introduction" icon="code">
    Explore social.plus API documentation.
  </Card>
</CardGroup>
