Authentication

Learn how to authenticate your users with QuickBlox.

Every user needs to authenticate with QuickBlox before using any QuickBlox functionality. When someone connects with an application using QuickBlox, the application needs to obtain a session token which provides temporary secure access to QuickBlox APIs. A session token is an opaque string that identifies a user and an application.

Visit our Key Concepts page to get an overall understanding of the most important QuickBlox concepts.

Before you begin

  1. Register a QuickBlox account. This is a matter of a few minutes and you will be able to use this account to build your apps.
  2. Configure QuickBlox SDK for your app. Check out our Setup page for more details.

Session token rights

There are different types of session tokens to support different use cases.

Session Token TypeDescription
Application session tokenThis kind of access token is needed to read the app data. Has only READ access to resources. The expiration time after the last REST API request is 2 hours.
User session tokenThe user token is the most commonly used type of token. This kind of access token is needed any time the app calls an API to read, modify or write a specific user's data on their behalf. Has READ/WRITE access to resources. The expiration time after the last REST API request is 2 hours.

Session management

By default, when a session gets expired, a new session with a new session token is created automatically. Thus, QuickBlox SDK stores a session token and uses it for all subsequent requests within the current session.

However, you can disable the automatic session creation. Use the setAutoCreateSession() method and pass false as its argument to disable the functionality.

QBSettings.getInstance().setAutoCreateSession(false);
QBSettings.getInstance().isAutoCreateSession = false

You can track session states using QBSessionManager class and SessionListener listener.

QBSessionManager.getInstance().addListener(new QBSessionManager.QBSessionListener() {
    @Override
    public void onSessionCreated(QBSession session) {
    // calls when session was created firstly or after it has been expired
    }
 
    @Override
    public void onSessionUpdated(QBSessionParameters sessionParameters) {
    // calls when user signed in or signed up
    // QBSessionParameters stores information about signed in user. 
    }
 
    @Override
    public void onSessionDeleted() {
    // calls when user signed Out or session was deleted 
    }
 
    @Override
    public void onSessionRestored(QBSession session) {
    // calls when session was restored from local storage
    }
 
    @Override
    public void onSessionExpired() {
    // calls when session is expired
    }
 
    @Override
    public void onProviderSessionExpired(String provider) {
    // calls when provider's access token is expired or invalid 
    }
});
QBSessionManager.getInstance().addListener(object : QBSessionManager.QBSessionListener {
    override fun onSessionCreated(session: QBSession) {
    // calls when session was created firstly or after it has been expired
    }

    override fun onSessionUpdated(sessionParameters: QBSessionParameters) {
    // calls when user signed in or signed up
    // QBSessionParameters stores information about signed in user.
    }

    override fun onSessionDeleted() {
    // calls when user signed Out or session was deleted
    }

    override fun onSessionRestored(session: QBSession) {
    // calls when session was restored from local storage
    }

    override fun onSessionExpired() {
    // calls when session is expired
    }

    override fun onProviderSessionExpired(provider: String) {
    // calls when provider's access token is expired or invalid
    }
})

Get session

At any time you can get details about your current session token.

QBSessionParameters sessionParameters = QBSessionManager.getInstance().getSessionParameters();
sessionParameters.getUserId();
sessionParameters.getUserLogin();
sessionParameters.getUserEmail();
sessionParameters.getSocialProvider();
sessionParameters.getAccessToken();
val sessionParameters = QBSessionManager.getInstance().getSessionParameters()
sessionParameters.userId
sessionParameters.userLogin
sessionParameters.userEmail
sessionParameters.socialProvider
sessionParameters.accessToken

Also, you can check whether you are logged in or not.

boolean isLoggedIn = QBSessionManager.getInstance().getSessionParameters() != null;
val isLoggedIn = QBSessionManager.getInstance().sessionParameters != null

Sign up user

Before you log in the user, you must create the user on QuickBlox. Recommendations are below:

  1. For POCs/MVPs: Create the user using the QuickBlox Dashboard or in client app with application session token.
  2. For production apps: Use the QuickBlox Create User API with API key on your backend to create the user when your user signs up in your app.

🚧

Security

It's recommended to disable permission to create users with application session on production apps once user creation is implemented on your backend.

You can create a user with application session token in client app by calling signUp() method.

final QBUser user = new QBUser();
user.setLogin("johnsmith");
user.setPassword("johnPassword");

QBUsers.signUp(user).performAsync(new QBEntityCallback<QBUser>() {
    @Override
    public void onSuccess(QBUser user, Bundle bundle) {
        
    }

    @Override
    public void onError(QBResponseException exception) {
        
    }
});
val user = QBUser()
user.login = "johnsmith"
user.password = "johnPassword"

QBUsers.signUp(user).performAsync(object : QBEntityCallback<QBUser> {
    override fun onSuccess(user: QBUser?, bundle: Bundle?) {
        
    }

    override fun onError(exception: QBResponseException?) {
        
    }
})

Log in user

QuickBlox provides four types of user authentication: login/email and password, social, phone number, and custom identity provider login.

Login/email and password

Log in a user just by using login (or email) and password. Other fields are optional. Thus, the QuickBlox server requests a user's database for a match. If there is a match, a user session is created.

final QBUser user = new QBUser();
user.setLogin("johnsmith");
user.setPassword("johnPassword");

QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
    @Override
    public void onSuccess(QBUser user, Bundle bundle) {
        
    }

    @Override
    public void onError(QBResponseException exception) {
        
    }
});
val user = QBUser()
user.login = "johnsmith"
user.password = "johnPassword"

QBUsers.signIn(user).performAsync(object : QBEntityCallback<QBUser> {
    override fun onSuccess(user: QBUser?, bundle: Bundle?) {
        
    }

    override fun onError(exception: QBResponseException?) {
        
    }
})

Social

Authenticate with QuickBlox using a social network access token.

String accessToken = "8b75a6c7191285499d890a81df4ee7fe49bc732a";
String accessTokenSecret = null;
String provider = QBProvider.FACEBOOK;

QBUsers.signInUsingSocialProvider(provider, accessToken, accessTokenSecret).performAsync(new QBEntityCallback<QBUser>() {
    @Override
    public void onSuccess(QBUser user, Bundle bundle) {
       
    }

    @Override
    public void onError(QBResponseException exception) {
        
    }
});
val accessToken = "Az9dgLfyK7tZBSAz9dgLfyK7tQNttIoaZA10niR68DO"
val accessTokenSecret: String? = null
val provider = QBProvider.FACEBOOK

QBUsers.signInUsingSocialProvider(provider, accessToken, accessTokenSecret).performAsync(object : QBEntityCallback<QBUser> {
    override fun onSuccess(user: QBUser?, bundle: Bundle?) {
        
    }

    override fun onError(exception: QBResponseException?) {
        
    }
})
ParametersDescription
providerA social network provider.
accessTokenAn access token received from the social network after a user authenticates with it.
accessTokenSecretA social network provider's access token secret.

Phone number

A sign-in with a phone number is supported with Firebase integration. In order to implement authentication via phone number functionality, follow this Firebase document.

Don't forget to enable phone number sign-in for your Firebase project. To learn how to do this, see this Firebase document.

You also need to sign in the user to Firebase. You can sing in the user only after completing a series of steps that involve sending a verification code to the user's phone, entering the verification code that Firebase sent to the user's phone, creating a PhoneAuthCredential object, etc. Refer this Firebase document for more details.

To log in the user to QuickBlox, use the signInUsingFirebase() method. Pass the project ID and ID token to the signInUsingFirebase(). The ID token is received as a result of the getIdToken() method.

private void refreshFirebaseAccessToken() {
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    firebaseUser.getIdToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
        @Override
        public void onComplete(@NonNull Task<GetTokenResult> task) {
            if (task.isSuccessful()) {
                // getting access token - successful
                if (task.getResult() != null) {
                    firebaseAccessToken = task.getResult().getToken();
                    // save access token
                }
            } else {
                // getting access token - unsuccessful
            }
        }
    });
}

private void loginByPhone() {
    QBUsers.signInUsingFirebase(firebaseProjectID, firebaseAccessToken).performAsync(new QBEntityCallback<QBUser>() {
        @Override
        public void onSuccess(QBUser user, Bundle bundle) {
            // a user has successful signed In
        }

        @Override
        public void onError(QBResponseException exception) {
            // handle error
        }
    });
}
private fun refreshFirebaseAccessToken() {
    val firebaseUser = FirebaseAuth.getInstance().currentUser

    firebaseUser?.getIdToken(false)?.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // getting access token - successful
            if (task.result != null) {
                firebaseAccessToken = task.result!!.token!!
                // save access token
            }
        } else {
            // getting access token - unsuccessful
        }
    }
}

private fun loginByPhone() {
    QBUsers.signInUsingFirebase(firebaseProjectID, firebaseAccessToken).performAsync(object : QBEntityCallback<QBUser>{
        override fun onSuccess(user: QBUser?, bundle: Bundle?) {
            // a user has successful signed In
        }

        override fun onError(exception: QBResponseException?) {
            // handle error
        }
    })
}

Pass the following arguments to the signInUsingFirebase() method.

ArgumentsDescription
firebaseProjectIDFirebase project ID. When you create a Firebase project, Firebase automatically assigns a unique ID to the project, but you can edit it during the project setup.
firebaseAccessTokenID token of the Firebase user. Created by Firebase when a user signs in to an app. This token is received as a result of getIdToken() method.

Custom identity provider

You can authenticate your application users from the external database with QuickBlox via Custom Identity Provider (CIdP). Just specify the user login and access token as a password to authenticate with QuickBlox. Review Custom Identity Provider page for more details on the feature.

String userLogin = "johnsmith";
String identityToken = "Fd4kxd37z58dS4d2Ye7wh3";
QBUser user = new QBUser();
user.setLogin(userLogin);
user.setPassword(identityToken);

QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
    @Override
    public void onSuccess(QBUser user, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException exception) {

    }
});
val userLogin = "johnsmith"
val identityToken = "Fd4kxd37z58dS4d2Ye7wh3"
val user = QBUser()
user.login = userLogin
user.password = identityToken

QBUsers.signIn(user).performAsync(object : QBEntityCallback<QBUser> {
    override fun onSuccess(user: QBUser?, bundle: Bundle?) {
       
    }

    override fun onError(exception: QBResponseException?) {
        
    }
})

🚧

This feature is available for customers on the Enterprise plan only. Take advantage of Enterprise features to unlock new value and opportunities for users. For more information and if you want to request a Demo, please contact us by mail: [email protected].

Log out user

If you have a user session, you can downgrade it to an application session by calling the logout() method.

QBUsers.signOut().performAsync(new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {
        
    }

    @Override
    public void onError(QBResponseException exception) {
        
    }
});
QBUsers.signOut().performAsync(object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
        
    }

    override fun onError(exception: QBResponseException?) {
        
    }
})

Destroy session token

To destroy an application session use the following code.

QBAuth.deleteSession().performAsync(new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {
        
    }

    @Override
    public void onError(QBResponseException exception) {
        
    }
});
QBAuth.deleteSession().performAsync(object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
        
    }

    override fun onError(exception: QBResponseException?) {
        
    }
})

Set existing session

Typically, a session token is stored in SDK after successful login and used for every subsequent API call. However, you may want to obtain and store the session on your server for better security. In this case, you can set application or user token into SDK using the QBAuth.startSessionWithToken() method, also before calling the method to get notified that the session has expired you need to add QBSessionListenerImpl() to QBSessionManager. Don't forget to log in user if you pass the application token.

QBSessionManager.getInstance().addListener(new QBSessionListenerImpl() {
    @Override
    public void onSessionExpired() {
     
    }
});

String token = "3Fjs1su8ery463gjd8hf";
QBAuth.startSessionWithToken(token);
QBSessionManager.getInstance().addListener(object : QBSessionListenerImpl() {
    override fun onSessionExpired() {
       
    }
})

val token = "3Fjs1su8ery463gjd8hf"
QBAuth.startSessionWithToken(token)

🚧

If you have version lower than 3.11.0, you can set the existing session token into SDK using the createActiveSession() method.

String token = "3Fjs1su8ery463gjd8hf";
QBSessionManager.getInstance().createActiveSession(token, tokenExpirationDate);
val token = "3Fjs1su8ery463gjd8hf"
QBSessionManager.getInstance().createActiveSession(token, tokenExpirationDate)

What’s Next