# Authentication and Authorization

[View on Github](https://github.com/CartoDB/carto-react-template)

{% hint style="warning" %}
**Note:** We are reducing our investment in CARTO for React and currently we discourage users from starting new projects with it.

CARTO for React is an opinionated framework with pre-built components and templates. This greatly speeds up the process to create React-based applications, but customization options are limited.

If you need further customization in React, or you want to build geospatial applications using **Vue, Angular, or any other Javascript-based framework**, we recommend going directly to the main CARTO for Developers documentation, including [CARTO + deck.gl](https://github.com/CartoDB/gitbook-documentation/blob/master/carto-for-developers/key-concepts/carto-for-deck.gl), which allows for maximum flexibility and scalability.
{% endhint %}

When building an application with CARTO for React, we can classify authentication and authorization in two structures:

* **Public applications:** The user does not need to log into the application. Access to data is provided through an API Access Token.
* **Private applications:** Requires that the end user performs a login using their CARTO credentials.

## Public applications <a href="#public-applications" id="public-applications"></a>

To create a public application, you'll need to:

* Obtain an API Access Token with access to all the data sources you want to use in your application.
  * Learn how to [create API Access Tokens](https://docs.carto.com/carto-user-manual/developers/managing-credentials/api-access-tokens#creating-an-api-access-token) using CARTO Workspace.
  * You can also prototype a Builder map with all the sources and [use the Map ID](https://docs.carto.com/carto-user-manual/maps/sharing-and-collaboration#publishing-options) as your API Access Token.
* Introduce the token in the application config (`src/store/initialStateSlice.js`) and remove the OAuth section.

The file `src/store/initialStateSlice.js` will look like this, and your application will be public to anyone accessing it.

```javascript
import { VOYAGER } from '@carto/react-basemaps';
import { API_VERSIONS } from '@deck.gl/carto';

export const initialState = {
  viewState: {
    latitude: 31.802892,
    longitude: -103.007813,
    zoom: 2,
    pitch: 0,
    bearing: 0,
    dragRotate: false,
  },
  basemap: VOYAGER,
  credentials: {
    apiVersion: API_VERSIONS.V3,
    apiBaseUrl: 'https://gcp-us-east1.api.carto.com',
    accessToken: 'TYPE HERE THE TOKEN'
  },
  googleApiKey: '', // only required when using a Google Basemap,
  // oauth: 
};
```

## Private applications

If you are building a private application, you first need to create a [SPA OAuth Client](https://docs.carto.com/carto-user-manual/developers/managing-credentials/spa-oauth-clients) and get a `Client ID`:

1. Go to the [Developers](https://docs.carto.com/carto-user-manual/developers) section inside CARTO Workspace
2. Create a new SPA OAuth Client with the URL `https://127.0.0.1:3000`
3. Copy the `Client ID` and introduce it at `src/store/initialStateSlice.js`.

When you have everything configured, the first screen for your application will be the following:

<figure><img src="https://3029946802-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FybPdpmLltPkzGFvz7m8A%2Fuploads%2Fgit-blob-e176313b42f86385a5666f480841ed2a21403213%2Foauth-login.png?alt=media&#x26;token=1a182097-f16e-49e7-a417-cc233e15ada6" alt=""><figcaption></figcaption></figure>

When your users click on the `Login with CARTO` button, the authentication protocol will start and your users will need to login using their CARTO credentials and allow access to the application. When the protocol finishes, a new access token with the required scopes will be sent. This access token will be used to access the data sources in the application, unless specific credentials are provided.

## Private applications using SSO

If you have enabled a [Single Sign-On (SSO)](https://docs.carto.com/carto-user-manual/settings/sso) integration and your users are authenticating to CARTO through your own Identity Provider (IdP), you can leverage the SSO setup in your CARTO for React private application.

To do so, obtain your `SSO Organization ID` from our Support team and introduce it at `src/store/initialStateSlice.js` here:

```typescript
  oauth: {
    domain: 'auth.carto.com',
    clientId: '', // type here your application clientId
    organizationId: '', // organizationId is required for SSO
    ...
    }
```

If you have [Just-in-time provisioning](https://docs.carto.com/carto-user-manual/settings/sso#just-in-time-provisioning) enabled in CARTO Workspace, the latest version of `src/hooks/Auth0.ts` contains the necessary changes to provide a seamless first-time experience for new users that didn't exist previously in CARTO.

Here's a video that shows the experience for new users in your app once SSO and Just-in-time provisioning have been enabled and configured in your application.

{% embed url="<https://vimeo.com/861971307/f5378d7bba>" %}

## CARTO 2 platform <a href="#carto-2-platform" id="carto-2-platform"></a>

If you are using the CARTO 2 platform, the process is slightly different.

If you want to create a public application, you can make the datasets public in the CARTO 2 Dashboard and then you can use the `default_public` API key when providing the credentials for accessing the dataset.

If you need to create a private application, you have two options:

* Generate an API key with access (read) to the datasets.
* Use OAuth for authentication.

### **Using API keys**

This is the traditional (legacy) way of working with private applications in the CARTO 2 platform. You need to generate an API key in the CARTO 2 Dashboard with access (read/select) to your datasets. After you have generated the API key, you introduce this API key in the initial state slice.

If you are using API keys, you need to implement your own authentication mechanism if you want to restrict access. Anyone can read your API key from the JavaScript source and you are potentially exposing more information than you want to.

### **Using OAuth**

CARTO 2 supports [OAuth](https://docs.carto.com/carto-for-developers/carto-for-react/library-reference/auth) to communicate with CARTO 2 REST APIs. OAuth is the preferred method to manage credentials, so we recommend you use this protocol for implementing **authentication & authorization** in your applications.

OAuth `scopes` are used to specify what permissions will users have to give to the application. For example, `datasets:r:table_name` will grant `read` access to the table `table_name`.

The workflow is:

1. You login with the desired scopes.
2. You get an API\_KEY (token) to call CARTO APIs but restricted to the requested scopes.

The first step you need to perform is to go to your CARTO 2 Dashboard and create a new OAuth app as described in the [documentation](https://docs.carto.com/authorization/#oauth-apps), in order to get the clientID for your application.

Then, you need to edit the `src/store/initialStateSlice.js` file and modify the clientId property in the `oauthInitialState` object. You can also modify the `scopes` property to specify what permissions you want to give the application.

If you want to force authentication in your application, so no unauthenticated users can access, you need to set the `forceOAuthLogin` property to `true` in the initialState object within the `src/store/appSlice.js` file. When you activate this flag, the first screen for your application will be the following:

<figure><img src="https://3029946802-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FybPdpmLltPkzGFvz7m8A%2Fuploads%2Fgit-blob-e176313b42f86385a5666f480841ed2a21403213%2Foauth-login.png?alt=media&#x26;token=1a182097-f16e-49e7-a417-cc233e15ada6" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
If your dataset is private and you want other users in your organization to be able to access it, you need to share it with them using the [`Share with colleagues`](https://carto.com/help/your-account/users/#sharing-private-maps-and-datasets-within-your-organization) option in the dashboard.
{% endhint %}

When your users click on the `Login with CARTO` button, the OAuth protocol flow will start and your users will be asked to allow access to their CARTO account.

If you just want to restrict access to some application features, you can use the [`OAuthLogin`](https://docs.carto.com/development-tools/carto-for-react/library-reference/auth#useoauthlogin) component. This will display a popup with the implicit OAuth flow.

Once the OAuth flow has been completed and the user has given consent to your application to access their CARTO account, you can obtain user credentials like this:

```javascript
import { selectOAuthCredentials } from '@carto/react-redux';
const credentials = useSelector(selectOAuthCredentials);
```

This credentials object can be used, for instance, when using a data source from a view:

```javascript
import aSource from 'data/sources/aSource';

dispatch(
  addSource({ ...aSource, credentials })
);
```

You can also use these credentials to call directly to our APIs from your models. You have an example of this in the [IsochroneModel](https://github.com/CartoDB/carto-react-template/blob/master/template-sample-app/template/src/data/models/isochroneModel.js) provided with the sample app template.

The credentials object contains the username and the API key, so you can use them to call any of the CARTO REST APIs endpoints.
