> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quickblox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 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 [Key Concepts](/docs/key-concepts) page to learn the most important QuickBlox concepts.

## Before you begin

1. Register a [QuickBlox account](https://admin.quickblox.com/signin). 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 [Setup](/sdks/android-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.

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    QBSettings.getInstance().setAutoCreateSession(false);
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    QBSettings.getInstance().isAutoCreateSession = false
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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
        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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
        }
    })
    ```
  </Tab>
</Tabs>

## Get session

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    QBSessionParameters sessionParameters = QBSessionManager.getInstance().getSessionParameters();
    sessionParameters.getUserId();
    sessionParameters.getUserLogin();
    sessionParameters.getUserEmail();
    sessionParameters.getSocialProvider();
    sessionParameters.getAccessToken();
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    val sessionParameters = QBSessionManager.getInstance().getSessionParameters()
    sessionParameters.userId
    sessionParameters.userLogin
    sessionParameters.userEmail
    sessionParameters.socialProvider
    sessionParameters.accessToken
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    boolean isLoggedIn = QBSessionManager.getInstance().getSessionParameters() != null;
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    val isLoggedIn = QBSessionManager.getInstance().sessionParameters != null
    ```
  </Tab>
</Tabs>

## 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](https://admin.quickblox.com/) or in client app with application session token.
2. **For production apps:** Use the [QuickBlox Create User API](https://docs.quickblox.com/reference/create-user) with [API key](/docs/application#create-api-key) on your backend to create the user when your user signs up in your app.

<Warning>
  Security

  It's recommended to [disable permission](/docs/application#set-session-permissions) to create users with application session on **production apps** once user creation is implemented on your backend.
</Warning>

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

        }
    })
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

        }
    })
    ```
  </Tab>
</Tabs>

### Social

Authenticate with QuickBlox using a social network access token.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

        }
    })
    ```
  </Tab>
</Tabs>

| Parameters        | Description                                                                          |
| ----------------- | ------------------------------------------------------------------------------------ |
| provider          | 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](https://firebase.google.com/docs/auth/android/phone-auth).

Don't forget to enable phone number sign-in for your Firebase project. To learn how to do this, see this [Firebase document](https://firebase.google.com/docs/auth/android/phone-auth#before-you-begin).

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](https://firebase.google.com/docs/auth/android/phone-auth#sign-in-the-user) 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.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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
            }
        });
    }
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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
            }
        })
    }
    ```
  </Tab>
</Tabs>

Pass the following arguments to the `signInUsingFirebase()` method.

| Arguments           | Description                                                                                                                                                       |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| firebaseProjectID   | 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. |
| firebaseAccessToken | 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](/docs/custom-identity-provider) page for more details on the feature.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

        }
    })
    ```
  </Tab>
</Tabs>

<Tip>
  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: [enterprise@quickblox.com](mailto:enterprise@quickblox.com.).
</Tip>

## Log out user

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    QBUsers.signOut().performAsync(new QBEntityCallback<Void>() {
        @Override
        public void onSuccess(Void aVoid, Bundle bundle) {

        }

        @Override
        public void onError(QBResponseException exception) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    QBUsers.signOut().performAsync(object : QBEntityCallback<Void> {
        override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

        }

        override fun onError(exception: QBResponseException?) {

        }
    })
    ```
  </Tab>
</Tabs>

## Destroy session token

To destroy an application session use the following code.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    QBAuth.deleteSession().performAsync(new QBEntityCallback<Void>() {
        @Override
        public void onSuccess(Void aVoid, Bundle bundle) {

        }

        @Override
        public void onError(QBResponseException exception) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    QBAuth.deleteSession().performAsync(object : QBEntityCallback<Void> {
        override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

        }

        override fun onError(exception: QBResponseException?) {

        }
    })
    ```
  </Tab>
</Tabs>

## 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](https://docs.quickblox.com/reference/authentication#application-vs-user-session-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]\(/sdks/android-authentication #log-in-user) if you pass the application token.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    QBSessionManager.getInstance().addListener(new QBSessionListenerImpl() {
        @Override
        public void onSessionExpired() {

        }
    });

    String token = "3Fjs1su8ery463gjd8hf";
    QBAuth.startSessionWithToken(token).performAsync(new QBEntityCallback<QBSession>() {
        @Override
        public void onSuccess(QBSession qbSession, Bundle bundle) {

        }

        @Override
        public void onError(QBResponseException exception) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    QBSessionManager.getInstance().addListener(object : QBSessionListenerImpl() {
        override fun onSessionExpired() {

        }
    })

    val token = "3Fjs1su8ery463gjd8hf"
    QBAuth.startSessionWithToken(token).performAsync(object : QBEntityCallback<QBSession>{
        override fun onSuccess(qbSession: QBSession?, bundle: Bundle?) {

        }

        override fun onError(exception: QBResponseException?) {

        }
    })
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    String token = "3Fjs1su8ery463gjd8hf";
    QBSessionManager.getInstance().createActiveSession(token, tokenExpirationDate);
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    val token = "3Fjs1su8ery463gjd8hf"
    QBSessionManager.getInstance().createActiveSession(token, tokenExpirationDate)
    ```
  </Tab>
</Tabs>
