> ## 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/react-native-setup) page for more details.

## Session token rights

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

| Application session token | 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. |

## Get session

You can check whether you have a session or not.

```JavaScript JavaScript theme={null}
QB.auth
  .getSession()
  .then(function (session) {
    // handle session
  })
  .catch(function (e) {
    // something went wrong
  });
```

## 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 `create()` method.

```JavaScript JavaScript theme={null}
const createUserParams = {
  fullName: 'Jack Sparrow',
  login: 'jack',
  password: 'jackpassword'
};

QB.users
  .create(createUserParams)
  .then(function (user) {
    // user created successfully
  })
  .catch(function (e) {
    // handle as necessary
  });
```

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

```JavaScript JavaScript theme={null}
const loginParams = {
  login: 'yourlogin',
  password: 'yourpassword'
};

// or through email
// const loginParams = {email: '[[email protected]](/cdn-cgi/l/email-protection)', password: 'garry5santos'};

QB.auth
  .login(loginParams)
  .then(function (info) {
    // signed in successfully, handle info as necessary
    // info.user - user information
    // info.session - current session
  })
  .catch(function (e) {
    // handle error
  });
```

### Social

Authenticate with QuickBlox using a facebook access token.

```JavaScript JavaScript theme={null}
const facebookToken = 'EAAJ1nlH9EaQphl8WmFIJBhFn8XLMBu8UWAyxx1Uz0JLwZDZD';

QB.auth
  .loginWithFacebook(facebookToken)
  .then(function (info) {
    // signed in successfully, handle info as necessary
    // info.user - user information
    // info.session - current session
  })
  .catch(function (e) {
    // handle error
  });
```

### 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://rnfirebase.io/auth/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/web/phone-auth#enable-phone-number-sign-in-for-your-firebase-project).

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.

```JavaScript JavaScript theme={null}
import React, { useState } from 'react';
import { Button, TextInput } from 'react-native';
import auth from '@react-native-firebase/auth';

function PhoneSignIn() {
  // If null, no SMS has been sent
  const [confirm, setConfirm] = useState(null);

  const [code, setCode] = useState('');

  // Handle the button press
  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
    setConfirm(confirmation);
  }

  async function confirmCode() {
    try {
      await confirm.confirm(code);
    } catch (error) {
      console.log('Invalid code.');
    }
  }

  if (!confirm) {
    return (
      <Button
        title="Phone Number Sign In"
        onPress={() => signInWithPhoneNumber('+1 650-555-3434')}
     />
    );
  }

  return (
    <>
      <TextInput value={code} onChangeText={text => setCode(text)}/>
      <Button title="Confirm Code" onPress={() => confirmCode()}/>
    </>
  );
}
```

To log in the user to QuickBlox, use the `loginWithFirebase()`. The ID token of the Firebase user is received as a result of the `getIdToken()` method.

```JavaScript JavaScript theme={null}
// Handle confirm code button press
  async function confirmCode() {
    try {
      const credential = auth.PhoneAuthProvider.credential(confirm.verificationId, code);
      let userData = await auth().currentUser.linkWithCredential(credential);
      setUser(userData.user);

      const idTokenResult = await firebase.auth().currentUser.getIdTokenResult();
      QB.auth
 			  .loginWithFirebase("Your projectId", idTokenResult.token)
        .then(function (info) {
          // signed in successfully, handle info as necessary
          // info.user - user information
          // info.session - current session
        })
        .catch(function (e) {
          // handle error
        });
    } catch (error) {
      if (error.code == 'auth/invalid-verification-code') {
        console.log('Invalid code.');
      } else {
        console.log('Account linking error');
      }
    }
  }
```

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

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

```JavaScript JavaScript theme={null}
const loginParams = {
  login: '4324',
  password: '8b75a6c7191285499d890a81df4ee7fe49bc732a'
};

QB.auth
  .login(loginParams)
  .then(function (info) {
    // signed in successfully, handle info as necessary
    // info.user - user information
    // info.session - current session
  })
  .catch(function (e) {
    // handle error
  });
```

<Warning>
  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.).
</Warning>

## Log out user

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

```JavaScript JavaScript theme={null}
QB.auth
  .logout()
  .then(function () {
    // signed out successfully
  })
  .catch(function (e) {
    // handle error
  });
```

## 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 `startSessionWithToken()` method, also before calling the method to get notified that the session has expired you need to add **SESSION\_EXPIRED** listener to **NativeEventEmitter**. Don't forget to [log in user](/sdks/react-native-authentication#log-in-user) if you pass the application token.

```JavaScript JavaScript theme={null}
import QB from 'quickblox-react-native-sdk';
import { NativeEventEmitter } from 'react-native';

const emitter = new NativeEventEmitter(QB.auth);

function sessionExpiredHandler(event) {
  // handle session expired event
}

emitter.addListener(QB.auth.EVENT_TYPE.SESSION_EXPIRED, sessionExpiredHandler);

const sessionToken = "8b75a6c7191285499d890a81df4ee7fe49bc732a"

QB.auth
  .startSessionWithToken(sessionToken)
  .then(function (session) {
    // handle session
  })
  .catch(function (e) {
    // handle error
  });
```

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

```JavaScript JavaScript theme={null}
const session = {
  applicationId: 76730,
  token: "8b75a6c7191285499d890a81df4ee7fe49bc732a",
  userId: 96752798,
};

QB.auth
  .setSession(session)
  .then((result) => {})
  .catch((error) => {});
```

The `setSession()` method accepts one argument of the object type that has the following fields:

| Field         | Required | Description              |
| ------------- | -------- | ------------------------ |
| applicationId | yes      | Application ID.          |
| token         | yes      | QuickBlox session token. |
| userId        | yes      | User ID.                 |

<Warning>
  You must call the `init()` method before calling the `setSession()` method. If you attempt to call the method without initializing SDK previously, the error will be returned.
</Warning>
