Tutorials

Android SDK Tutorial 2 – Authentication and Authorization

Integrate Applozic Android SDK to get started with your own chat application!
Google+ Pinterest LinkedIn Tumblr

This tutorial is Part 2 of a multi-part series covering Applozic Android SDK integration into an Android app.

Our goal is to complete the following steps in this tutorial:

  1. Learn how to generate an access token for your application
  2. Create a User Object
  3. Register/Login the user
  4. Update password for user
  5. Update User Details

What are Authentication and Authorization?

In the simplest terms, we can classify them as:

  • Authentication: Proving your identity to an entity
  • Authorization: The ability to interact with an entity
Authentication vs Authorization

Authentication and authorization with APIs have a lot of value, some of them are:

  • Authenticate that calls to the API are done by registered users only
  • Maintain a record to track which user is making the requests
  • Track the total usage of the API calls across users and applications
  • Notify any user who exceeds their plan limit
  • Apply different permission levels to different users

Now that we have learnt the need for authentication and authorization, let’s get started with the first step in this tutorial.

Generating Access Token

Access Token URL (Authentication URL) is required to ensure your platforms are safe from unauthorized access. This can be configured by the Application admin in Applozic Dashboard for authenticating users from your backend server.

Setup Access Token URL in Dashboard

  1. Login to Applozic Dashboard
  2. Go to Dashboard. Select Application -> Action -> Edit -> Security.
  3. Enter your server URL for authentication in the “Access Token URL” field.
Application screen in Dashboard
Security Tab in Edit Application settings
Note: Configured Access Token URL should accept POST request with data passed as request body in form-url-encoded.

You can now use an API testing tool like Postman to verify your access.

Follow our documentation here to learn the parameters and response for the same.

Creating a User Object

To create your first user, you can instantiate a new User object using the following code:

User user = new User();          
user.setUserId(userId); 
//userId it can be any unique user identifier

user.setDisplayName(displayName); 
//displayName is the name of the user which will be shown in chat messages

user.setEmail(email); //optional  

user.setAuthenticationTypeId(User.AuthenticationType.APPLOZIC.getValue()); 
//User.AuthenticationType.APPLOZIC.getValue() for password verification 
from Applozic server and User.AuthenticationType.CLIENT.getValue() for access Token 
verification from your server set access token as password

user.setPassword(""); 
//optional, you can leave it blank for testing purposes. 

user.setImageLink(""); //optional,pass your image link

Applozic.connectUser(context, user, new AlLoginHandler() {
@Override
public void onSuccess(RegistrationResponse registrationResponse, Context context) 
{ 
// After successful registration with Applozic server the callback will come here 
}
@Override
public void onFailure(RegistrationResponse registrationResponse, Exception exception) 
{
// If any failure in registration the callback  will come here 
}
}); 
Note: If it is a new user, a user account will get created else existing user will be logged in to the application.
PropertyDescription
userIdNeeds to be unique. +,*,? are not allowed chars in userId.
displayName (Optional)displayName is the name of the user which will be shown in chat messages. If not set, userId will be shown to other users.
email (Optional)You can set an email id if required.
AuthenticationType (Optional)User.AuthenticationType.APPLOZIC.getValue() for password verification from Applozic server and User.AuthenticationType.CLIENT.getValue() for access token verification from your server set access token as password
imageLink (Optional)The url of the image that you want to display for the user. If not set, you can set a placeholder image for the user.
password (Optional)You can leave it blank for testing purposes. If you want to add additional security by verifying password from your server check Applozic access token .

Check out how the user creation is handled in the Applozic sample app here.

Adding additional fields in User Object

If you need to add some additional fields to a User object that is not a property of the existing User object then you can set the additional fields in the metadata of the User.
For example, if you need to add fields like Department, Designation, Team etc to a User, then you can add them to the User metadata.

Map<String, String> metadata = new HashMap<>(); 
metadata.put("Department" , "Engineering"); 
metadata.put("Designation" , "Software Engineer"); 
metadata.put("Team" , "Device Team"); 
user.setMetadata(metadata);

Register/Login the User

You can Authenticate the user with Applozic using a method similar to this:

Applozic.connectUser(context, user, new AlLoginHandler() {
@Override
public void onSuccess(RegistrationResponse registrationResponse, Context context) 
{
// After successful registration with Applozic server the callback will come here 
}
@Override
public void onFailure(RegistrationResponse registrationResponse, Exception exception) 
{
// If any failure in registration the callback will come here 
}
});

If the user is a new user, a new account will be created for the same.
On the other hand, if the user is an existing user, they will be logged in to Applozic.

Based on the success or failure of registration/login, you can set up corresponding actions in your application. For example, on success you could launch the chat screen for the user, and onFailure you could throw an error message based on the exception and the response received.

If you need to check if a user is already logged in, you can do so using a method similar to this:

if (Applozic.isConnected(context)) {
// logic here
}

Check out how User Login is handled in the Applozic sample app here.

Update password for User

You can update login user password using a method similar to this:

Note: Call the password update method in an Async task or background thread 
as its a server call

String response = 
UserService.getInstance(this).processUpdateUserPassword(oldpassword, newPassword);

if(!TextUtils.isEmpty(response) && MobiComKitConstants.SUCCESS.equals(response))
   {
     //Password updated successfully
   } else {
     //Password update failed
   }

Update User details

If you want to update details of the user, you can do so using a method similar to this:

User user = new User();
 user.setImageLink("IMAGE_URL");
 user.setDisplayName("USER_NEW_DISPLAY_NAME");

 UserService.getInstance(this).updateUser(user, new AlCallback() {
      @Override
       public void onSuccess(Object response) {
           Log.i("User", "Update success ");
        }

      @Override
       public void onError(Object error) {
            Log.i("User", "Update failed ");
        }
  });

End of Tutorial 2

In this Applozic Android SDK tutorial, we have learnt how to:

  • Generate an access token for your application
  • Create a User Object
  • Register/Login the user
  • Update password for user
  • Update User Details

You are now ready to move to Tutorial 3, Conversations!

Author

Anurag is a Technical Writer and technology enthusiast who enjoys science fiction and PC gaming.