This guide covers user authentication and device registration for social.plus UIKit. Authentication is essential for personalizing the user experience and enabling social features.
New to social.plus Authentication? For comprehensive authentication concepts, security patterns, and backend implementation, see the SDK Authentication Guide. This guide focuses specifically on UIKit implementation.

Prerequisites

Before setting up authentication, ensure you have:

API Credentials

Your API key and region from social.plus Console

UIKit Installed

social.plus UIKit installed in your project
Coming from First Steps? If you followed the First Steps guide, you’ve already completed basic authentication. This guide provides comprehensive details and production-ready patterns.

Get Your API Credentials

Access social.plus Console

1

Visit Console

Go to social.plus Console and sign in to your account.
2

Navigate to Security

In the left sidebar, click SettingsSecurity.
3

Copy Credentials

Find your API Key and note your Region. You’ll need both for authentication.

Regional Configuration

social.plus operates in multiple regions for optimal performance and compliance:
apiRegion: "us"
endpoint: "api.us.amity.co"
Region Consistency: Your API region must match the region where your social.plus application was created. Mismatched regions will cause authentication failures.

Authentication Modes

social.plus UIKit supports two authentication modes depending on your security requirements:
Quick Setup (API Key Only)Perfect for development, testing, and proof-of-concept applications:
// Development authentication - API key only
<AmityUiKitProvider
  apiKey="YOUR_API_KEY"
  apiRegion="us"
  userId="user-123"
  displayName="John Doe"
>
  {/* Your app */}
</AmityUiKitProvider>
Development mode is great for getting started quickly, but should not be used in production applications.

Learn About Auth Tokens

Understanding auth tokens, server-to-server verification, and backend implementation patterns

Device Registration

Understanding Device Binding

Important: Once registered, a device is permanently tied to a userId until explicitly unregistered or inactive for 90+ days. Plan your authentication flow carefully.
When you authenticate a user with social.plus UIKit, you’re registering the current device with that user’s ID. This device will receive all messages and notifications belonging to that user.

Platform Implementation

Choose your platform for device registration:
import AmityUIKit

// 1. Register device with user (basic)
AmityUIKitManager.registerDevice(
    withUserId: "user-123",
    displayName: "John Doe"
)

// 2. Register device with auth token (production)
AmityUIKitManager.registerDevice(
    withUserId: "user-123",
    displayName: "John Doe",
    authToken: "auth-token-from-backend"
)

// 3. Register for push notifications (optional)
UIKitManager.registerDeviceForPushNotification("device-token") { isSuccess, error in
    if isSuccess {
        print("Push notifications registered")
    } else {
        print("Push registration failed: \(error?.localizedDescription ?? "")")
    }
}
Push Notifications: social.plus UIKit doesn’t manage push permission requests or token creation. Your app must handle these and pass the device token.

User Management

User ID Guidelines

Your user identification strategy is crucial for a smooth user experience:

Session Management

1

User Login

When a user logs into your app, register them with social.plus. The device will be tied to this user.
2

Session Persistence

The SDK automatically maintains sessions across app launches. No additional action needed.
3

User Logout

When users log out, properly unregister the device to prevent unauthorized access:
// Unregister device on logout
AmityUIKitManager.unregisterDevice()
Unregistering a device is synchronous. Once called, the SDK disconnects from the server and wipes the user session.
4

User Switching

To switch users, unregister the current user first, then register the new user:
// 1. Unregister current user
await amitySDK.unregisterDevice();

// 2. Register new user
await amitySDK.registerDevice(newUserId, newDisplayName);

Advanced Configuration

Environment Management

Organize your configuration for different environments:
const config = {
  apiKey: "dev_b24c28bc...",
  apiRegion: "us",
  debug: true,
  // No auth token needed for development
};

Error Handling

Implement comprehensive error handling for authentication:
const AuthenticationService = {
  async authenticateUser(userId: string, displayName: string, authToken?: string) {
    try {
      if (authToken) {
        // Production mode with auth token
        await amitySDK.registerDevice(userId, displayName, authToken);
      } else {
        // Development mode
        await amitySDK.registerDevice(userId, displayName);
      }
      
      console.log('Authentication successful');
      return { success: true };
    } catch (error) {
      console.error('Authentication failed:', error);
      
      // Handle specific error types
      if (error.code === 'INVALID_API_KEY') {
        return { success: false, error: 'Invalid API credentials' };
      } else if (error.code === 'INVALID_AUTH_TOKEN') {
        return { success: false, error: 'Invalid or expired auth token' };
      } else if (error.code === 'NETWORK_ERROR') {
        return { success: false, error: 'Network connection failed' };
      }
      
      return { success: false, error: 'Authentication failed' };
    }
  },
  
  async logoutUser() {
    try {
      await amitySDK.unregisterDevice();
      return { success: true };
    } catch (error) {
      console.error('Logout failed:', error);
      return { success: false, error: 'Logout failed' };
    }
  }
};

Backend Integration

For production applications, you’ll need to implement auth token generation on your backend:

Backend Auth Token Implementation

Learn how to implement secure auth token generation, token validation, and server-to-server communication with social.plus

Quick Backend Example

Here’s a simplified example of auth token generation:
// Example Node.js backend endpoint
app.post('/api/auth/social-plus-token', authenticateUser, async (req, res) => {
  try {
    // User is already authenticated by your middleware
    const { userId } = req.user;
    
    // Generate auth token for social.plus
    const authToken = await generateSocialPlusAuthToken(userId);
    
    res.json({ authToken });
  } catch (error) {
    res.status(500).json({ error: 'Failed to generate auth token' });
  }
});
Security Note: Never generate auth tokens on the client side. They must be created by your secure backend after verifying the user’s identity.

Troubleshooting


Next Steps

Now that authentication is configured, you can explore social.plus UIKit features:

User ID Guidelines

Your user identification strategy is crucial for a smooth user experience:

Session Management

Device Binding: Once registered, a device is permanently tied to a user ID until explicitly unregistered or inactive for 90+ days. Plan your authentication flow carefully.
1

User Login

When a user logs into your app, register them with social.plus:
// Register the current device with the user
await amitySDK.register(userId, displayName);
2

Session Persistence

The SDK automatically maintains sessions across app launches. No additional action needed.
3

User Logout

When users log out, properly unregister the device:
AmitySDK.unregisterDevice { success, error in
    if success {
        // Device unregistered successfully
        self.returnToLoginScreen()
    } else {
        // Handle error
        print("Logout failed: \(error?.localizedDescription ?? "")")
    }
}
4

User Switching

To switch users, unregister the current user first, then register the new user:
// 1. Unregister current user
await amitySDK.unregisterDevice();

// 2. Register new user
await amitySDK.register(newUserId, newDisplayName);

Advanced Configuration

Environment Management

Organize your configuration for different environments:
const config = {
  apiKey: "dev_b24c28bc...",
  apiRegion: "us",
  debug: true,
  enableLogging: true,
  // Optional: Use test endpoints
  apiEndpoint: "https://api.staging.amity.co"
};

Error Handling

Implement comprehensive error handling for authentication:
const AuthenticationService = {
  async authenticateUser(userId: string, displayName: string) {
    try {
      await amitySDK.register(userId, displayName);
      console.log('Authentication successful');
      return { success: true };
    } catch (error) {
      console.error('Authentication failed:', error);
      
      // Handle specific error types
      if (error.code === 'INVALID_API_KEY') {
        return { success: false, error: 'Invalid API credentials' };
      } else if (error.code === 'NETWORK_ERROR') {
        return { success: false, error: 'Network connection failed' };
      } else if (error.code === 'INVALID_USER_ID') {
        return { success: false, error: 'Invalid user ID format' };
      }
      
      return { success: false, error: 'Authentication failed' };
    }
  },
  
  async logoutUser() {
    try {
      await amitySDK.unregisterDevice();
      return { success: true };
    } catch (error) {
      console.error('Logout failed:', error);
      return { success: false, error: 'Logout failed' };
    }
  }
};

Security Best Practices


Troubleshooting


Next Steps

Now that authentication is configured, you can explore social.plus UIKit features:
1

Initialize SDK

Initialize the SDK in your Application class or main activity:
import com.amity.socialcloud.sdk.AmityCoreClient
import com.amity.socialcloud.uikit.AmityUIKit

// In Application class or MainActivity
AmityCoreClient.setup(
    apiKey = "YOUR_API_KEY",
    region = AmityRegionalEndpoint.US // or EU, SG
)
2

Register User

Register and authenticate the user:
AmityCoreClient.login("unique_user_id")
    .displayName("User Display Name")
    .build()
    .submit()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ user ->
        // User registered successfully
        Log.d("Auth", "User registered: ${user.displayName}")
    }, { error ->
        // Handle registration error
        Log.e("Auth", "Registration failed", error)
    })
3

Launch UIKit

Start social.plus UIKit activities:
import com.amity.socialcloud.uikit.AmityUIKit

// Launch social features
AmityUIKit.openSocialHome(this)

// Or launch specific features
AmityUIKit.openChatHome(this)

Web/React Setup

1

Initialize Provider

Set up the AmityUiKitProvider in your React app:
import React from 'react';
import { AmityUiKitProvider } from '@amityco/ui-kit';

function App() {
  return (
    <AmityUiKitProvider
      apiKey="YOUR_API_KEY"
      apiRegion="US" // or "EU", "SG"
      userId="unique_user_id"
      displayName="User Display Name"
    >
      {/* Your app content */}
    </AmityUiKitProvider>
  );
}
2

Use Components

Import and use social.plus components:
import { AmityUiKitSocial } from '@amityco/ui-kit';

function SocialPage() {
  return (
    <div className="social-container">
      <AmityUiKitSocial />
    </div>
  );
}

React Native Setup

1

Initialize Provider

Wrap your app with the provider:
import React from 'react';
import {
  AmityUiKitProvider,
  AmityUiKitSocial,
} from 'amity-react-native-social-ui-kit';

export default function App() {
  return (
    <AmityUiKitProvider
      apiKey="YOUR_API_KEY"
      apiRegion="US" // or "EU", "SG"
      userId="unique_user_id"
      displayName="User Display Name"
    >
      <AmityUiKitSocial />
    </AmityUiKitProvider>
  );
}

Flutter Setup

1

Initialize App

Set up the AmityApp widget:
import 'package:amity_uikit_beta_service/amity_uikit_beta_service.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AmityApp(
        apiKey: 'YOUR_API_KEY',
        apiRegion: 'US', // or 'EU', 'SG'
        userId: 'unique_user_id',
        displayName: 'User Display Name',
        child: AmitySocialHomePage(),
      ),
    );
  }
}

Authentication Best Practices

User ID Guidelines

Session Management

Device Binding: A device registered with a specific userId will be permanently tied to that user until you deliberately unregister the device, or until the device has been inactive for more than 90 days.
1

Registration

Register the device with the user ID when the user logs in to your app.
2

Session Persistence

The SDK automatically maintains the session across app launches.
3

Logout

Properly unregister the device when the user logs out:
AmitySDK.unregisterDevice { success, error in
    if success {
        print("Device unregistered successfully")
    }
}

Configuration Options

Optional Parameters

Environment Configuration

const config = {
  apiKey: "dev_api_key",
  apiRegion: "US",
  debug: true,
  logging: true
};

Troubleshooting


Next Steps