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.

Get session

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

QB.getSession(function (error, session) {
})

Create session

To create an application session, use the following code.

QB.createSession(function(error, result) {
  // callback function
});

To create a user session, use the following code.

var params = { login: "garry", password: "garry5santos" };

// or through email
// var params = {email: '[email protected]', password: 'garry5santos'};

// or through social networks (Facebook / Twitter)
// var params = {provider: 'facebook', keys: {token: 'AM46dxjhisdffgry26282352fdusdfusdfgsdf'}};

QB.createSession(params, function(error, result) {
  // callback function
});

Sign up user

If a current user doesn't exist, you can create them by calling create() method.

var params = {
  login: login,
  password: "someSecret",
  full_name: "QuickBlox Test"
};

QB.users.create(params, function(error, result) {
  if (error) {
    done.fail("Create user error: " + JSON.stringify(error));
  } else {
  }
});

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

Standard login lets you log in a user just by login (or email) and password. Other fields are optional. Thus, the QuickBlox server requests a users database for a match. If there is a match, a user session is created.

var params = { login: "garry", password: "garry5santos" };

// or through email
// var params = {email: '[email protected]', password: 'garry5santos'};
QB.login(params, function(error, result) {
  // callback function
});

Social

Authenticate with QuickBlox using a social network access token.

var provider = "facebook"; 
var accessToken = "EAAWGrT9ljYYBAEZBuj1lGwmbLASHHBRmpM18pABBzdl29h5EQN0ZAfpKMZA5sCZCsb3c2tI78HpWvvP8eeZBJsflL8QWDZCrWVS5MIIAG7WgKp3I8OtZAukUzZBd92tZARFVcbuSb6yyyVobchhwfrZB4mC4ZARClvfNZCKdGbxPmO3VAsfquxK3ZAndgVQTJ8nqbro2ObA3ZCqVPUiAZDZD";
var accessTokenSecret = null;
QB.createSession({
  provider:provider,
  keys:{
    token:accessToken,
    secret:accessTokenSecret 
  }
},function(error, result) {
  if (error) {
  } else {
  }
});
ParametersDescription
providerAuthentication provider.
keysAccess keys:
- token. The access token received from the social network after a user authenticates with it.
- secret. A 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.

To send a verification code to the user's phone and sign in the user on Firebase with the received verification code, use the snippet below.

/**
 * @param {string} PhoneNumber
 */
FirebaseHelper.prototype.signInWithPhoneNumber = function (PhoneNumber) {
  firebase.auth().languageCode = "en";
  window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
    "firebase__recaptcha_container",
    {
      size: "normal",
      callback: function () {
        firebase
          .auth()
          .signInWithPhoneNumber(PhoneNumber, window.recaptchaVerifier)
          .then(function (confirmationResult) {
            document.querySelector(".get_code").style.display = "none";
            document.querySelector(".login").style.display = "block";
            // SMS sent. Prompt user to type the code from the message, then sign the user with confirmationResult.confirm(code).
            window.confirmationResult = confirmationResult;
          })
          .catch(function (error) {
            console.log("Error:", error);
            if (error.message) alert(error.message);
            document.querySelector("#firebase__recaptcha_container").innerHTML =
              "";
            document
              .querySelector("#phoneNumber")
              .nextElementSibling.classList.add("filled");
          });
      },
    }
  );
  window.recaptchaVerifier.render();
};

var firebaseHelper = new FirebaseHelper();

firebaseHelper.signInWithPhoneNumber(phoneNumber);

To log in the user to QuickBlox, use the login() method and pass authParams to it. The ID token of the Firebase user is received as a result of the getIdToken() method.

var code = "confirmation code";

window.confirmationResult.confirm(code).then(function (result) {
  result.user.getIdToken(true).then(function (idToken) {
    var authParams = {
      provider: "firebase_phone",
      firebase_phone: {
        access_token: idToken,
        project_id: "Your projectId",
      },
    };
    QB.login(authParams, function (error, user) {
      if (error) {
        // check the error
      } else {
        // user - logged-in user (response from https://docs.quickblox.com/reference/authentication#log-in)
      }
    });
  });
}).catch(function (error) {
  console.error(error);
});

Pass the following arguments to the login() method.

ArgumentsRequiredDescription
authParamsyesSpecifies Firebase authentication parameters that should be set.

The authParams object includes the following fields.

FieldsDescription
providerAuthentication provider. Possible values: facebook, firebase_phone.
firebase_phoneSpecifies the firebase_phone object fields that should be set:
- project_id. Firebase 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.
- access_token. ID 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 ID and access token as a password to authenticate with QuickBlox. Review Custom Identity Provider page for more details on the feature.

var params = { login: "4324", password: "8b75a6c7191285499d890a81df4ee7fe49bc732a" };

QB.login(params, function(error, result) {
  // callback function
});

🚧

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 logout() method.

QB.logout(function(error) {
  // callback function
});

Session expiration

The expiration time for a session token is 2 hours. If you will perform a query with an expired token, you will receive an error: "Required session does not exist". In this case, you have to recreate the session token.
In JS SDK since version 2.14.1 we have a listener to find if the session token has expired.

QB.chat.onSessionExpiredListener = function(error){
    if (error) {
        console.log('onSessionExpiredListener - error: ', error);
    } else{
        console.log('The session has expired.');
    }
}

If you use JS SDK version early then 2.14.1 in order to found out the session has expired you should use code below to initialize JS SDK.

var APPLICATION_ID = 41;
var AUTH_KEY = "lkjdueksu7392kj";
var AUTH_SECRET = "iiohfdija792hj";
var ACCOUNT_KEY = "sdjfnksnlk2bk1k34kb";
var CONFIG = { debug: true,
    on: {
        sessionExpired: async function(handleResponse, retry) {
        console.log('The session has expired.');
        },
    }, };
 
QB.init(APPLICATION_ID, AUTH_KEY, AUTH_SECRET, ACCOUNT_KEY, CONFIG);

Destroy session token

To destroy a session, use the following code.

QB.destroySession(function(error) {
  // callback function
});

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, since the version JS SDK 2.14.1, you can set the existing session token into SDK using the startSessionWithToken(sessionToken, callBack) method. It's can be application or user token. Don't forget to Init and log in user if you pass the application token.

QB.startSessionWithToken(sessionToken, function(err, mySession){
    if (err){
        console.log('Error in start session with token');
    } else {
        console.log('session data: ', mySession);
    }
});

What’s Next