Skip to main content
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:
  • United States
  • Europe
  • Singapore
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:
  • Development Mode
  • Production Mode
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:
  • iOS
  • Android
  • Web/React
  • React Native
  • Flutter
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:
Best Practices:
  • Use your internal user ID or UUID
  • Ensure IDs are unique across your entire user base
  • Keep IDs consistent across all platforms
Avoid:
  • Email addresses (users might change emails)
  • Phone numbers (users might change numbers)
  • Display names (not unique)
Valid Characters:
  • Alphanumeric characters (a-z, A-Z, 0-9)
  • Underscores (_) and hyphens (-)
  • Maximum length: 255 characters
Invalid Characters:
  • Spaces or special characters (@, #, $, etc.)
  • Emojis or unicode characters
Security:
  • Don’t expose sensitive information in user IDs
  • Consider hashing user IDs if needed
  • Implement server-side validation
Scalability:
  • Use a consistent ID format
  • Plan for user merging scenarios
  • Consider ID migration strategies

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:
  • iOS
  • Android
  • Web/React
// 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:
  • Development
  • Production
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

Invalid API Key (401 Error):
  • Verify API key is correct and not truncated
  • Check that the API key matches your console account
  • Ensure no extra spaces or characters
Invalid Auth Token (403 Error):
  • Verify auth token is properly generated by your backend
  • Check token hasn’t expired
  • Ensure token format matches social.plus requirements
Region Mismatch:
  • Verify region matches your console setup
  • Check endpoint URLs are correct
  • Confirm region code format (us/eu/sg)
Device Already Registered:
  • Unregister existing user first
  • Wait for previous session to properly close
  • Clear app data if needed (development only)
Invalid User ID Format:
  • Remove special characters and spaces
  • Check user ID length (max 255 characters)
  • Use only alphanumeric characters and underscores
Session Conflicts:
  • Ensure proper logout before switching users
  • Check for multiple provider instances (Web/React)
  • Verify device registration cleanup
iOS:
  • Ensure registration is called on main thread
  • Check for proper app lifecycle handling
  • Verify push notification setup if using
Android:
  • Implement proper Activity/Fragment lifecycle
  • Check for ProGuard/R8 obfuscation issues
  • Verify session handler implementation
Web/React:
  • Ensure single provider instance at app root
  • Import CSS styles for proper component rendering
  • Check for CORS issues in development
React Native:
  • Verify native module linking
  • Check platform-specific permissions
  • Test on physical devices for push notifications
Flutter:
  • Check session handler implementation
  • Verify platform permissions are configured
  • Ensure proper async/await usage

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:
Best Practices:
  • Use your internal user ID or UUID
  • Ensure IDs are unique across your entire user base
  • Keep IDs consistent across all platforms
Avoid:
  • Email addresses (users might change emails)
  • Phone numbers (users might change numbers)
  • Display names (not unique)
Valid Characters:
  • Alphanumeric characters (a-z, A-Z, 0-9)
  • Underscores (_) and hyphens (-)
  • Maximum length: 255 characters
Invalid Characters:
  • Spaces or special characters (@, #, $, etc.)
  • Emojis or unicode characters
Security:
  • Don’t expose sensitive information in user IDs
  • Consider hashing user IDs if needed
  • Implement server-side validation
Scalability:
  • Use a consistent ID format
  • Plan for user merging scenarios
  • Consider ID migration strategies

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:
  • iOS
  • Android
  • Web/React
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:
  • Development
  • Production
  • Enterprise
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

Client-Side Applications:
  • Store API keys in environment variables
  • Never commit API keys to version control
  • Use different keys for development and production
Server-Side Authentication (Recommended):
  • Implement server-side token generation
  • Use short-lived authentication tokens
  • Validate users on your backend before issuing tokens
Input Validation:
  • Validate user IDs before registration
  • Sanitize display names
  • Implement rate limiting for authentication attempts
Session Security:
  • Monitor for unusual authentication patterns
  • Implement proper logout flows
  • Consider implementing session timeouts

Troubleshooting

Invalid API Key (401 Error):
  • Verify API key is correct and not truncated
  • Check that the API key matches your console account
  • Ensure no extra spaces or characters
Region Mismatch (403 Error):
  • Verify region matches your console setup
  • Check endpoint URLs are correct
  • Confirm region code format (us/eu/sg)
Network Issues:
  • Test internet connectivity
  • Check firewall/proxy settings
  • Verify DNS resolution for amity.co domains
Invalid User ID Format:
  • Remove special characters and spaces
  • Check user ID length (max 255 characters)
  • Use only alphanumeric characters and underscores
Device Already Registered:
  • Unregister existing user first
  • Wait for previous session to properly close
  • Clear app data if needed (development only)
Display Name Issues:
  • Ensure display name is not empty
  • Check for special character restrictions
  • Verify UTF-8 encoding for international names
iOS:
  • Ensure setup is called on main thread
  • Check for proper delegate implementations
  • Verify bundle identifier permissions
Android:
  • Implement proper Activity/Fragment lifecycle
  • Check for ProGuard/R8 obfuscation issues
  • Verify network permissions in manifest
Web/React:
  • Ensure provider wraps all UIKit components
  • Check for CORS issues in development
  • Verify React version compatibility
React Native:
  • Check platform-specific permissions
  • Verify native module linking
  • Test on physical devices, not just simulators
Flutter:
  • Check pubspec.yaml dependencies
  • Verify platform permissions are configured
  • Test hot reload vs full restart

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

  • Use a unique, persistent identifier for each user
  • Avoid using email addresses or phone numbers directly
  • Consider using UUIDs or your system’s internal user IDs
  • Maintain the same user ID across app sessions
  • Ensure user IDs remain consistent across different platforms
  • Don’t change user IDs after initial registration
  • Never expose sensitive user information in user IDs
  • Use a hash or encoded value if needed
  • Implement proper server-side validation

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:
  • iOS
  • Android
AmitySDK.unregisterDevice { success, error in
    if success {
        print("Device unregistered successfully")
    }
}

Configuration Options

Optional Parameters

For enterprise customers with custom endpoints:
// Web/React
<AmityUiKitProvider
  apiKey="YOUR_API_KEY"
  apiEndpoint="https://api.custom-domain.com"
  // ... other props
/>
For server-side authentication (recommended for production):
// Use secure token instead of API key
<AmityUiKitProvider
  authToken="secure_server_generated_token"
  // ... other props
/>

Environment Configuration

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

Troubleshooting

Invalid API Key: Verify your API key is correct and matches your console account.Wrong Region: Ensure the region matches where your social.plus application was created.Network Issues: Check internet connectivity and firewall settings.
Duplicate User: User IDs must be unique within your application.Invalid Characters: User IDs should only contain alphanumeric characters and underscores.Session Conflicts: Ensure proper logout before registering a different user.
iOS: Check that you’re calling setup methods on the main thread.Android: Ensure proper lifecycle management in activities/fragments.Web: Verify the provider wraps all components that need social.plus context.

Next Steps