QuickBlox Documentation

QuickBlox provides powerful Chat API and SDK to add real-time messaging and video calls to your web and mobile apps. Learn how to integrate QuickBlox across multiple platforms.

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 will need 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 Type

Description

Application session token

This 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 token

The 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.

Sign up user

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

let user = QBUUser()
user.login = "myLogin"
user.fullName = "myFullName"
user.password = "myPassword"

QBRequest.signUp(user, successBlock: { response, user in
    
}, errorBlock: { (response) in               
    
})
QBUUser *user = [[QBUUser alloc] init];
user.login = @"myLogin";
user.fullName = @"myFullName";
user.password = @"myPassword";

[QBRequest signUp:user successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nonnull user) {
        
} errorBlock:^(QBResponse * _Nonnull response) {

}];

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 users database for a match. If there is a match, a user session is created.

QBRequest.logIn(withUserLogin: "userLogin", password: "userPassword", successBlock: { (response, user) in
    //Block with response and user instances if the request is succeeded.
}, errorBlock: { (response) in
    //Block with response instance if the request is failed.
})
[QBRequest logInWithUserLogin:@"userLogin" password:@"userPassword" successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nonnull tUser) {
    //Block with response and user instances if the request is succeeded.
} errorBlock:^(QBResponse * _Nonnull response) {
    //Block with response instance if the request is failed.
}];

Social

Authenticate with QuickBlox using a social network access token.

let socialProvider = "facebook" 
let accessToken = "Az9dgLfyK7tZBSAz9dgLfyK7tQNttIoaZA10niR68DO" //Social provider's access token.

QBRequest.logIn(withSocialProvider: socialProvider, accessToken: socialProviderAccessToken, accessTokenSecret: nil, successBlock: { (response, user) in
    //Block with response and user instances if the request is succeeded.
}, errorBlock: { (response) in
    //Block with response instance if the request is failed.
})
NSString *socialProvider = @"facebook"; //Social provider. Posible values: facebook, twitter.
NSString *accessToken = @"EAAECKEsf4G4BAGQaE4yA1basdfxxxJSUQ2HS7fUllXQj5V1jdZAykykbVMmnJ8kiiVyGTU4Spj6emBFz0mZBRlNtaJwJGhChCquYRSZBb7vmsfl64jhy7QUo54SesQWERTYUa2jDHzQDWedXjWVTbmM4pvtbsai63jgZA16iCDHKb"; //Social provider access token.

[QBRequest logInWithSocialProvider:socialProvider accessToken:accessToken accessTokenSecret:nil successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nonnull tUser) {
    //Block with response and user instances if the request is succeeded.
} errorBlock:^(QBResponse * _Nonnull response) {
    //Block with response instance if the request is failed.
}];

Parameters

Description

socialProvider

A social network provider.

accessToken

An access token received from the social network after a user authenticates with it.

accessTokenSecret

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.

Send a verification code to the user's phone and sign in the user on Firebase with the received verification code. Then, log in the user to QuickBlox. To log in the user, use the logIn() method. Pass the project ID and ID token to the logIn() method. The ID token is received as a result of getIdToken() method.

import Firebase
import FirebaseUI

private func performPhoneLogin() {
    guard let authUI = FUIAuth.defaultAuthUI() else {
        return
    }
    authUI.delegate = self
    let phoneAuth = FUIPhoneAuth(authUI: authUI)
    authUI.providers = [phoneAuth]
    phoneAuth.signIn(withPresenting: self, phoneNumber: nil)
}

//MARK: - FUIAuthDelegate
extension AuthViewController: FUIAuthDelegate {
    func authUI(_ authUI: FUIAuth, didSignInWith authDataResult: AuthDataResult?, error: Error?) {
        if error != nil {
            return
        }
        guard let authDataResult = authDataResult else {
            return
        }
        
        let myFirebaseprojectID = "thisIsProjectIDFromFirebase" //Firebase project ID
        
        authDataResult.user.getIDToken(completion: { (token, completionError) in
            guard let token = token else {
                return
            }
            QBRequest.logIn(withFirebaseProjectID: myFirebaseprojectID, accessToken: token, successBlock: { (response, user) in
                //Block with response and user instances if the request is succeeded.
            }) { (response) in
                //Block with response instance if the request is failed.
            }
        })
    }
}
@import FirebaseCore;
@import FirebaseAuth;
@import FirebaseUI.FUIPhoneAuth;


- (void)performPhoneLogin {
    FUIAuth *authUI = [FUIAuth defaultAuthUI];
    authUI.delegate = self;
    FUIPhoneAuth *phoneAuth = [[FUIPhoneAuth alloc] initWithAuthUI:authUI];
    authUI.providers = @[phoneAuth];
    [phoneAuth signInWithPresentingViewController:self phoneNumber:nil];
}

NSString *myFirebaseprojectID = @"thisIsProjectIDFromFirebase"; //Firebase project ID

// MARK: - FUIAuthDelegate delegate
- (void)authUI:(FUIAuth *)authUI didSignInWithAuthDataResult:(FIRAuthDataResult *)authDataResult error:(NSError *)error {
    if (error != nil) {
        return;
    }
    [authDataResult.user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable __unused completionError) {
        [QBRequest logInWithFirebaseProjectID:myFirebaseprojectID accessToken:token successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nonnull tUser) {
            //Block with response and user instances if the request is succeeded.
        } errorBlock:^(QBResponse * _Nonnull response) {
            //Block with response instance if the request is failed.
        }];
    }];
}

Pass the following arguments to the logIn() method.

Arguments

Description

myFirebaseprojectID

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.

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 login and access token as a password to authenticate with QuickBlox. Review Custom Identity Provider page for more details on the feature.

let externalUserLogin = "myQBLogin" //External backend user ID. Posible values: externalUser.ID, externalUser.phoneNumber, externalUser.email, or any other field you would like to use as a unique identifier.
let externalUserPassword = "Fd4kxd37z58dS4d2Ye7wh3" //Token received by the user during authentication on the external backend

QBRequest.logIn(withUserLogin: externalUserLogin, password: externalUserPassword, successBlock: { (response, user) in
    //Block with response and user instances if the request is succeeded.
}, errorBlock: { (response) in
    //Block with response instance if the request is failed.
})
NSString *externalUserLogin = @"123456789"; //External backend user ID. Posible values: externalUser.ID, externalUser.phoneNumber, externalUser.email, or any other field you would like to use as a unique identifier.
NSString *externalUserPassword = @"EAAECKEsf4G4BAGQaE4yA1basdfxxxJSUQ2HS7fUllXQj5V1j..."; //Token received by the user during authentication on the external backend

[QBRequest logInWithUserLogin:externalUserLogin password:externalUserPassword successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nonnull tUser) {
    //Block with response and user instances if the request is succeeded.
} errorBlock:^(QBResponse * _Nonnull response) {
    //Block with response instance if the request is failed.
}];

🚧

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.

QBRequest.logOut(successBlock: { (response) in
    
}, errorBlock: { (response) in
    
})
[QBRequest logOutWithSuccessBlock:^(QBResponse * _Nonnull response) {
        
} errorBlock:^(QBResponse * _Nonnull response) {

}];

Destroy session token

To destroy a session, use the following code.

QBRequest.destroySession(successBlock: { (response) in
    
}, errorBlock: { (response) in
    
})
[QBRequest destroySessionWithSuccessBlock:^(QBResponse * _Nonnull response) {

} errorBlock:^(QBResponse * _Nonnull response) {

}];

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 the existing session token into SDK using the start(withDetails:updateSessionBlock:) method.

let sessionDetails = QBASession()
sessionDetails.token = "f23d03bd2341a1f923b7d4c1fbee97af1cd296f2"

// updateSessionBlock executes synchronously on background thread and you are allowed to execute synchronous URL request
// and to block a background thread from executing until you receive updated credentials
// by the end of updateSessionBlock you should call startSessionWithDetails: with updated credentials

QBSession.current.start(withDetails: sessionDetails, updateSessionBlock: {
    // Execute synchronous URL request to retrieve new token from custom server
    // Until the end of this block all the operations will be paused
    let updatedSessionDetails = QBASession()
    updatedSessionDetails.token = "new token"//new token from custom server
    // Start Updated Session
    QBSession.current.start(withDetails: updatedSessionDetails)
})
QBASession *sessionDetails = [QBASession new];
sessionDetails.token = @"f23d03bd2341a1f923b7d4c1fbee97af1cd296f2";

// updateSessionBlock executes synchronously on background thread and you are allowed to execute synchronous URL request
// and to block a background thread from executing until you receive updated credentials
// by the end of updateSessionBlock you should call startSessionWithDetails: with updated credentials

[[QBSession currentSession] startSessionWithDetails:sessionDetails updateSessionBlock:{
    // Execute synchronous URL request to retrieve new token from custom server
    // Until the end of this block all the operations will be paused
    QBASession *updatedSessionDetails = [QBASession new];
    session.token = @"new token";//new token from custom serve
    // Start Updated Session
    [[QBSession currentSession] startSessionWithDetails:updatedSessionDetails];
}];

Updated 6 months ago


What's Next

Users

Authentication


Learn how to authenticate your users with QuickBlox.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.