Authentication and Authorization

Applozic uses a password based authentication system to authenticate users.
An authenticated user, upon connecting, gets a JWT token that is used to authenticate API calls.
This JWT token is stored locally and is refreshed when it expires. All this is handled internally by the SDK. All you have to worry about is connecting a valid user.

If however you already use an access token in your backend and you can change the authentication type to CLIENT and pass your access token in the password field.

What is a User?

A user represents an entity that is “using” the Applozic chat application.
A user is identified by its userId. Users send and receive messages, join/leave groups etc. A user can also be logged in multiple devices and platforms.
In the context of the Client SDKs, the user is usually the “person” authenticated and logged in currently.
However as stated above, the term user can be loosely used to denote anyone using the chat.

What is the difference between a User and Contact?

Technically, both User and Contact are the same thing. They are both identified by their userId. Both send and receive messages etc.
The term “user” can also refer to a “contact”.

The difference between them is that:
Contact is a client term. It is used to refer to a “user” that is on the receiving end of the messages.
Users are persisted (stored locally) as Contact objects in the client SDKs.
The user receiving messages from the user logged in your session is referred to as a Contact.

Pre-built customizable chat UI - Authentication

Once you have all the libraries added from Installation, the next step is to setup user registration and authentication for chat.

Why do you need this?
Authentication helps you do two things

  1. It helps you to identify users i.e. differentiate between the users who have access to chat from those who do not have access to chat.
  2. Setup user profiles usually necessary for chat

Where should I put this?
The authentication process allows you to create users or log them into chat whenever necessary. This is usually done along with the login or registration of users within your app i.e. within the login or register buttons in your app.

A sample button's in the image below

Another thing you must understand is, in case of Applozic SDK both Registering a new user and loging in an existing user has the same process and code.

This code is available for both Objective C and Swift, which will be explained later with samples.

The user itself though is identified using a unique Userid and Password that has to be defined by you.

User ID

For a new user of your app to be able to access Applozic chat, it is necessary that the user is registered with Applozic system with a unique USERID.

This userid is then used to not only allow your users to login into chat but also to identify the user within Applozic system, especially useful when you are trying to download the chat history of a particular user.

In the installation step we setup Cocopods to install libraries necessary for Applozic Chat.

The next step in the process is to Register or login your user into the chat.

But before we can do this. There are methods you would require to implement this stage. These methods and the process to import these methods are as follows

Importing Methods for Authentication

The method file that we need here is the ALChatManager file, depending on which SDK you use the steps associated with this file also changes.

For ApplozicSwift SDK ::

  1. Download the ALChatManager.swift here and add the downloaded ALChatManager.swift in your project, add the bridging header if it asks.

  2. Once done replace "applozic-sample-app" with your App-ID. In this case, "applozic-sample-app" is in the ALChatManager.swift file and you can find your Applozic APP-ID here in console

For Applozic Core SDK::

The process is as follows

Once you have the App ID, replace it in ALChatManager.h file

📘

Have Question Or Suggestion?

You can drop us your query at [email protected]

Register/Login the User

After adding the files into your project, you are ready to create the process to login or register the user to chat.

📘

The Userid itself can be in alphanumeric with the size not exceeding 150 characters and does not allow + * ? : characters in it.

Using ApplozicSwift or Applozic Core SDK

The process is divided into 3 sections i.e.

  • Creating "ALUser" and Passing user details
  • Saving these details
  • Registering or Login in the User:- Don't forget to replace "applozic-sample-app" with your App ID from your Applozic account

📘

Recommended Authentication

We recommend using our Access Token based authentication as the password. More details regarding the same can be found here---> Access Token

For ApplozicSwift SDK ::

// Creating "ALUser" and Passing user details.
  let alUser = ALUser()
  alUser.userId = "USER-ID" // NOTE : +,*,? are not allowed chars in userId.
  alUser.email = "EMAIL-ID" // User email Id
  alUser.imageLink = ""   // User's profile image link.
  alUser.displayName = "USER-DISPLAY-NAME"  // User's Display Name
  alUser.password = "USER-PASSWORD" // User password
  alUser.authenticationTypeId = Int16(APPLOZIC.rawValue) // Authentication type id default is APPLOZIC
 
  // Saving these details.
  ALUserDefaultsHandler.setUserAuthenticationTypeId(alUser.authenticationTypeId)
 
 // Registering or Login in the User.
 ALChatManager.shared.connectUser(alUser, completion: {response, error in
      if error != nil {
         print("Error while logging \(String(describing: error))")
      } else {
         print("Successful login")
      }
  })
// Creating "ALUser" and Passing user details
ALUser * user = [[ALUser alloc] init];
[user setUserId:@"USER-ID"]; // NOTE : +,*,? are not allowed chars in userId.
[user setDisplayName:@"USER-DISPLAY-NAME"]; // User's Display Name
[user setPassword:@"USER-PASSWORD"]; // User password
[user setAuthenticationTypeId:(short)APPLOZIC];// Authentication type APPLOZIC handle by Applozic Server or CLIENT Authentication Handle by your own server
[user setImageLink:@"user_profile_image_link"]; // User's profile image link.


[ALUserDefaultsHandler setUserAuthenticationTypeId:(short)APPLOZIC];

[[ALChatManager shared] connectUser:user completion:^(ALRegistrationResponse * response, NSError * error) {
     if (error){
         NSLog(@"Error in login to applozic %@", error.localizedDescription);
         return;
     }
     NSLog(@"Applozic login success");
}];

For Applozic Core SDK ::

//Creating "ALUser" and Passing user details
// Except UserId all the other parameters are optional

ALUser *alUser = [[ALUser alloc] init];
[alUser setUserId:@"testUser"]; //NOTE : +,*,? are not allowed chars in userId.
[alUser setDisplayName:@"Applozic Test"]; // Display name of user 
[alUser setContactNumber:@""];// formatted contact no
[alUser setImageLink:@"user_profile_image_link"];// User's profile image link.
[alUser setPassword:@"testpassword"]; //Password for the user

//Saving the details
[ALUserDefaultsHandler setUserId:alUser.userId];
[ALUserDefaultsHandler setEmailId:alUser.email];
[ALUserDefaultsHandler setDisplayName:alUser.displayName];
[ALUserDefaultsHandler setUserAuthenticationTypeId:(short)APPLOZIC];
[ALUserDefaultsHandler setPassword:alUser.password];


//Registering or Loging in the User
ALChatManager * chatManager = [[ALChatManager alloc] initWithApplicationKey:@"applozic-sample-app"]; // Replace this with your App ID
[chatManager connectUserWithCompletion:alUser withHandler:^(ALRegistrationResponse *rResponse, NSError *error) {
        
      if (!error)
      {
        //Applozic registration successful
      }
      else
      {
          NSLog(@"Error in Applozic registration : %@",error.description);
      }
}];

🚧

Note

Please remember you have to log in once and only after you log out you must log in again. Use below code to check if the user is already logged in.

Checking if a user is connected

To check if the user is logged in, use this code:

if ([ALUserDefaultsHandler isLoggedIn]) {
    // User is Connected 
}
if ALUserDefaultHandler.isLoggedIn() { 
    // User is Connected 
}

Adding additional fields in User

Sometimes you might need to add custom parameters or fields to your User data which can be used within your application to personalize chat.

If you are looking at such a requirement, the following code can help you add additional fields to the METADATA of your user. These values can be retrieved using the Unique Userid that you would have set in previous steps.

In the following sample code below
Designation
City
Country
are the additional fields/information that you might want to add to a chat user.

NSMutableDictionary *userMetaData = [[NSMutableDictionary alloc] init];
 [userMetaData setValue:@"Software engineer" forKey:@"designation"];
 [userMetaData setValue:@"Bengaluru" forKey:@"city"];
 [userMetaData setValue:@"India" forKey:@"country"];
 [user setMetadata:userMetaData];
var userMetaData = NSMutableDictionary()
 userMetaData["designation"] = "Software engineer"
 userMetaData["city"] = "Bengaluru"
 userMetaData["country"] = "India"
 user.metadata = userMetaData

TOKEN - Validation

With data security being one of our biggest priorities, we recommend that you use an access token based methodology to validate your Users.

The general process flow is shown below

To begin with you would need to create an Access Token URL at your server side, please follow the instructions here---> Access Token URL

Once done please follow the process below for Client side validation

  1. In your ALChatManager.m file, please add the following method to ALDefaultChatViewSettings
[ALUserDefaultsHandler setUserAuthenticationTypeId:(short)CLIENT];
ALUserDefaultsHandler.setUserAuthenticationTypeId(CLIENT)
  1. Once you finish the setup, you would have to generate a unique Access Token for each user that you register with Applozic.

This Access Token would replace your Password Parameter in your ALUser object under Register/Login setup mentioned above.

[user setPassword:<YOUR ACCESS TOKEN>]; //set password value
user.setPassword(<YOUR ACCESS TOKEN>)

Password update

You can use the below method to update login user password, you need to pass the old password and new password to update

ALUserService *alUserService = [[ALUserService alloc] init];
    [alUserService updatePassword:@"OLD-PASSWORD" withNewPassword:@"NEW-PASSWORD" withCompletion:^(ALAPIResponse *alAPIResponse, NSError *theError) {
 
        if (!theError) {
            NSLog(@"Password updated successfully");
        }
    }];
let userService = ALUserService()
    userService.updatePassword("OLD-PASSWORD", withNewPassword: "NEW-PASSWORD") { (alApiResponse, error) in
        if (error == nil) {
            print("Password updated successfully")
        }
    }

Update User Details

Use this API to update the user details after the user has been registered.

Example: In the below method we are updating imageLinkFromServer and other parameters will be nil you will have to pass the nil in case if you don't want to update.

ALUserService *userService = [ALUserService new];
    [userService updateUserDisplayName:@"DISPLAY-NAME" andUserImage:@"PROFILE-IMAGE-URL-LINK" userStatus:nil withCompletion:^(id theJson, NSError *error) {
 
        if (error) {
            NSLog(@"Failed to update the user details %@", error.localizedDescription);
            return;
        }
    }];
let userService = ALUserService()
        userService.updateUserDisplayName("DISPLAY-NAME", andUserImage: "PROFILE-IMAGE-URL-LINK", userStatus: nil) { (response, error) in
            if error == nil {
                // success
            }
        }

Get logged In userId of Applozic user

Use the below setting to get the current login userId in Applozic

[ALUserDefaultsHandler getUserId];
ALUserDefaultsHandler.getUserId()

Build your UI from scratch - Authentication

Setup Application

Let's start with the Installation part.

First, Initialise the SDK with the App ID you got from the Applozic Dashboard after sign up . Then next, set up the App ID in the place of applozic-sample-app put your App ID.

👍

Custom UI Sample App

You can check out this Custom UI sample app which can be used as a reference. Also, you can clone it and try locally.

Initialise an instance of ApplozicClient to use throughout your app. You can create this in either your app delegate file or a ViewController class, for example:

There are two ways to Initialise

Create ApplozicClient variable and access it.

@import ApplozicCore;

@property (strong, nonatomic) ApplozicClient *applozicClient;
import Applozic
  
 var  applozicClient = ApplozicClient()
  1. One way is without real-time updates delegate callbacks
self.applozicClient = [[ApplozicClient alloc ]initWithApplicationKey:@"applozic-sample-app"]; //Pass App ID here
applozicClient = ApplozicClient(applicationKey: "applozic-sample-app") as ApplozicClient //Pass App Id here
  1. Another way is with real-time update delegate callbacks
self.applozicClient = [[ApplozicClient alloc]initWithApplicationKey:@"applozic-sample-app" withDelegate:self]; //Pass your App ID
applozicClient = ApplozicClient(applicationKey: "applozic-sample-app", with: self) as ApplozicClient //Pass your App ID

📘

How to get applicationKey?

You need to sign up at https://www.applozic.com. Under the Install section, App ID will be present.

Register/Login the User From Client

In the case of Applozic SDK, both Registering a new user and logging in an existing user has the same process and code.

This code is available for both Objective C and Swift, which are explained below with samples.

The user itself though is identified using a unique Userid and Password that has to be defined by you.

UserId
For a new user of your app to be able to access Applozic chat, it is necessary that the user is registered with Applozic system with a unique USERID.

This userId is then used to not only allow your users to login into chat but also to identify the user within Applozic system, especially useful when you are trying to download the chat history of a particular user.

📘

The UserId itself can be in alphanumeric with the size not exceeding 150 characters and does not allow +*?/: characters in it.

ALUser *user = [[ALUser alloc] init];
user.userId = @"USER-ID"; // NOTE : +,*,? are not allowed chars in userId.
user.password = @"USER-PASSWORD"; // User password
user.displayName = @"USER-DISPLAY-NAME"; // User's Display Name
user.email = @"EMAIL-ID"; // User email Id
user.imageLink = @""; // Pass Profile image URL link
user.authenticationTypeId = APPLOZIC; // Authentication type id default is APPLOZIC
    
[ALUserDefaultsHandler setUserAuthenticationTypeId:user.authenticationTypeId];
    
[self.applozicClient loginUser:user withCompletion:^(ALRegistrationResponse *response, NSError *error) {
        
     if (!error) {
         NSLog(@"Login success");
      }
}];
let user = ALUser()
user.userId = "USER-ID" // NOTE : +,*,? are not allowed chars in userId.
user.password = "PASSWORD" // Pass the password
user.displayName = "USER-DISPLAY-NAME"  // User's Display Name
user.imageLink = ""  // User's profile image link.
user.email = "EMAIL-ID" // User email Id
user.authenticationTypeId = Int16(APPLOZIC.rawValue)  // Authentication type id default is APPLOZIC
 
 ALUserDefaultsHandler.setUserAuthenticationTypeId(user.authenticationTypeId)
 
 applozicClient.loginUser(user, withCompletion: { response, error in
        if error == nil {
            print("Login success")
         }
 })

Here is an explanation some of the fields of a User object:

Name

Description

Optional

USER-ID

This is the identifier for your user.

Needs to be unique.
(+,*,? are not allowed)

No

USER-DISPLAY-NAME

This is the name for the user.
It is supposed to be shown in chat to other users.

If not set, userId is used instead.

Yes

EMAIL-ID

An email for the user.

Yes

authenticationTypeId

Int16(APPLOZIC.rawValue) or APPLOZIC tells the Applozic backend to handle the authentication itself.

Int16(CLIENT.rawValue) or CLIENT
tells the Applozic backend that the client will provide the access token. In this case, pass the access token in the user’s password field.

Yes
(Default is Int16(APPLOZIC.rawValue)) or APPLOZIC

imageLink

Public URL Link to the profile image for the user.

Yes

USER-PASSWORD

Password for the user.
The first time you set a value and send it to the server, the password will be set.

Can be left blank too.

Yes

metadata

Sometimes you might need to add custom parameters or fields to your User data which can be used within your application to personalize chat.

Yes

Important things to note

Sign-up/Login

When you call this method for a new user with a fresh userId, a new user will be created in the backend and then logged in. If you have provided a password, that will also be set for this user.

Use your own access token/authentication

If you want to use your own access token and authentication, set the authentication type to Int16(CLIENT.rawValue) or CLIENT and pass your token as the password.
See link: https://docs.applozic.com/docs/access-token-url for more information.

Password

The password can be left blank. However if you connect the user again with some string in the password field later, it will be updated without any warning.


What’s Next
Did this page help you?