# Authentication in browsers

To use browsers authentication with the SDK you need to use the client.loginWithOAuth(...) from the CogniteClient instance of the SDK.

loginWithOAuth(...) automatically handles authentication of the user and responds when the client get a 401 response (not logged in) from the API.

In this article:

# Why not use API keys?

We strongly recommended that you don't use API keys in web applications since the API key is easily readable by everyone with access to the application. Another restriction is that all users of your app share the same API key. This means that all users have the same access level, you lose tracing/auditing per user, keys are not time limited etc.

# Access tokens

The solution to avoid using API keys is to use access tokens instead. These are short lived tokens which grants the user access to CDF. The application gets an access token by asking the user to login to the identity provider (Google, Active Directory etc) of a CDF project.

# Authentication flow

The flow for the user using your application:

  1. The user uses your app on this URL: https://my-app.com/some/path?someQuery=someValue
  2. The SDK redirects the user to the project's identity provider.
  3. After a successful login, the browser redirects the user to the URL: https://my-app.com/some/path?someQuery=someValue&access_token=someToken&id_token=someToken.
  4. The app initializes again and calls createClientWithOAuth again.
  5. The SDK sees the query parameters access_token and id_token in the URL. It parses them and remove them from the URL.
  6. The SDK is authenticated (using the access token from the URL).

The access token expires after some time and results in the user get 401 from CDF again. A new authentication process will be triggered by the SDK.

# How to authenticate with the SDK?

There are two ways to authenticate using the SDK:

# Authentication with redirects

When authenticating with redirects the current browser window is redirected to the identity provider for the user to sign in. After login the same browser window redirects back to your application.

TIP

You can find a running example application using redirects here (opens new window).

# Simple example

import { CogniteClient, REDIRECT } from '@cognite/sdk';
const client = new CogniteClient({ ... });
client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  // default is redirect
  // but can be explicitly specified:
  onAuthenticate: REDIRECT,
});
// then use the SDK:
const assets = await client.assets.retrive({ id: 23232789217132 });
1
2
3
4
5
6
7
8
9
10
11

The first time this is run, the user gets a 401-response from CDF in the first call to client.assets. This triggers the SDK to perform a redirect of the browser window to authenticate.

The second time client.assets is called, the SDK is authenticated and the call succeeds.

# Customize redirect URL

If you want a different redirect URL back to your app after a successful/unsuccessful login, implement this:

import { CogniteClient, REDIRECT } from '@cognite/sdk';
const client = new CogniteClient({ ... });
client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  onAuthenticate: login => {
    login.redirect({
      redirectUrl: 'https://my-app.com/successful-login',
      errorRedirectUrl: 'https://my-app.com/unsuccessful-login', // We encourage you to use this property as well. If not specified it will default to redirectUrl
    });
  },
});
1
2
3
4
5
6
7
8
9
10
11

# Authentication with popups

When authenticating with popups the current browser window of your application remains the same, but a new window will pop-up asking the user to sign in to the identity provider. After a successful sign-in, the popup-window automatically closes.

TIP

You can find a running example application using popups here (opens new window).

# Simple example

import { CogniteClient, POPUP, isLoginPopupWindow, loginPopupHandler } from '@cognite/sdk';
if (isLoginPopupWindow()) {
  loginPopupHandler();
  return;
}
const client = new CogniteClient({ ... });
client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  onAuthenticate: POPUP,
});
// then use the SDK:
const assets = await client.assets.retrive({ id: 23232789217132 });
1
2
3
4
5
6
7
8
9
10
11
12
13
14

The first time this runs, the user gets a 401 response from CDF in the first call to client.assets. This triggers the SDK to perform authentication of the user using a popup-window. A new window pops up with the login screen of the identity provider.

After a successful login the popup-window redirects back to your app (the same URL as the main browser window) where sdk.loginPopupHandler is executed and handles the tokens in the URL and closes the window.

It is important that sdk.loginPopupHandler runs when the popup window is redirected back to your app (otherwise the authentication process will fail).

After a successful authentication process, the SDK automatically retries the client.assets request and eventually resolves and returns the correct result.

# Customize redirect URL

If you want a different redirect URL back to your application after a successful / unsuccessful login:

import { CogniteClient, POPUP } from '@cognite/sdk';
const client = new CogniteClient({ ... });
client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  onAuthenticate: login => {
    login.popup({
      redirectUrl: 'https://my-app.com/popup-handler',
      errorRedirectUrl: 'https://my-app.com/unsuccessful-login', // We encourage you to use this property as well. If not specified it will default to redirectUrl
    });
  },
});
1
2
3
4
5
6
7
8
9
10
11

This only affects the popup-window.

# Advanced

# Manually trigger authentication

To avoid waiting for the first 401-response to occur, you can trigger the authentication flow manually like this:

client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
});
await client.authenticate(); // this also returns a boolean based on if the user successfully authenticated or not.
1
2
3
4

# Cache access tokens

If you already have a access token, you can use it to skip the authentication flow (see this section to learn how to get hold of the token). If the token is invalid or timed out, the SDK triggers a standard auth-flow on the first 401-response from CDF.

client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  accessToken: 'ACCESS TOKEN FOR THE PROJECT HERE',
});
1
2
3
4

TIP

client.authenticate() will still override this and trigger a new authentication flow.

# Skip authentication

You can skip the authentication like this:

client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  onAuthenticate: (login) => {
    login.skip();
  },
});
1
2
3
4
5
6

# Combine different authentication methods

If you want to use the redirect method in the initialization of your app and the popup-method later (to not lose the state of your app) you can implement something like this:

client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  onAuthenticate: login => {
    // some check:
    if (itShouldRedirect) {
      login.redirect({ ... });
    } else {
      login.popup({ ... });
    }
  },
});
1
2
3
4
5
6
7
8
9
10
11

# Tokens

If you need access to the tokens (access token, id token) from the login flow, you can add a callback like this:

client.loginWithOAuth({
  project: 'YOUR PROJECT NAME HERE',
  onTokens: ({ accessToken, idToken }) => {
    // your logic here
  },
});
1
2
3
4
5
6

# Next steps

Learn more about the authentication process in this guide.

Last Updated: 9/10/2020, 12:11:40 PM