sdk-auth

Auth module for different authorization flows of commercetools platform API

Install

Node.js

npm install --save @commercetools/sdk-auth

Browser

<script src="https://unpkg.com/@commercetools/sdk-auth/dist/commercetools-sdk-auth.umd.min.js"></script>
<script>
  // global: CommercetoolsSdkAuth
</script>

Initialization

Creates an auth client to handle authorization against the commercetools platform API.

Named arguments (options)

  1. host (String): the host of the OAuth API service
  2. projectKey (String): the key of the project to assign the default scope to (optional).
  3. authType (String): Auth type performed in the auth request (default Basic).
  4. token (String): A token which will be sent in Authorization header. If not provided, we calculate it from credentials.
  5. disableRefreshToken (boolean): whether the API should generate a refresh token
  6. credentials (Object): the client credentials for authentication (clientId, clientSecret)
  7. scopes (Array): a list of scopes (default manage_project:{projectKey}) to assign to the OAuth token
  8. fetch (Function): A fetch implementation which can be e.g. node-fetch or unfetch but also the native browser fetch function. Only needs be be passed if not globally available (e.g. through isomorphic-fetch)

Usage example

import SdkAuth from '@commercetools/sdk-auth'
import fetch from 'node-fetch'

const authClient = new SdkAuth({
  host: 'https://auth.commercetools.com',
  projectKey: 'test',
  disableRefreshToken: false,
  credentials: {
    clientId: '123',
    clientSecret: 'secret',
  },
  scopes: ['view_products:test', 'manage_orders:test'],
  fetch,
})

const token = await authClient.clientCredentialsFlow()

NOTE: All auth flow methods can accept also an additional configuration for overriding config properties which were set during object creation.

const token = await authClient.clientCredentialsFlow({
  scopes: ['view_products:test', 'manage_orders:test'],
})

Authorization Flows

Client Credentials Flow

Fetches access token using Client Credentials Flow from the commercetools platform API.

Argument

  1. config (Object): Optional configuration which can override config properties given when building authClient object.

Usage example

await authClient.clientCredentialsFlow()
// {
//      "access_token": "...",
//      "expires_in": 172800, // lifetime of access_token in seconds
//      "expires_at": 1542287072875, // UTC datetime in unix timestamp format when the token expires
//      "scope": "manage_project:{projectKey}",
//      "token_type": "Bearer",
// }

Customer Password Flow

Fetches access token using Password Flow from the commercetools platform API.

Argument

  1. credentials (Object): Object with named arguments containing user credentials
    • username (String): customer email
    • password (String): customer password
  2. config (Object): Optional configuration which can override config properties given when building authClient object.

Usage example

await authClient.customerPasswordFlow(
  {
    username: '...',
    password: '...',
  },
  {
    disableRefreshToken: false,
  }
)
// {
//      "access_token": "...",
//      "expires_in": 172800,
//      "expires_at": 1542287072875,
//      "scope": "manage_project:{projectKey}",
//      "token_type": "Bearer",
//
//      "refresh_token" is missing because it was disabled in configuration
//
// }

Client Password Flow

Same as customerPasswordFlow but performs auth request against /oauth/token endpoint instead.

Argument

  1. credentials (Object): Object with named arguments containing user credentials
    • username (String): client email
    • password (String): client password
  2. config (Object): Optional configuration which can override config properties given when building authClient object.

Usage example

await authClient.clientPasswordFlow({
  username: '...',
  password: '...',
})
// {
//      "access_token": "...",
//      "expires_in": 172800,
//      "expires_at": 1542287072875,
//      "scope": "manage_project:{projectKey}",
//      "refresh_token": "...",
//      "token_type": "Bearer",
// }

Refresh Token Flow

Fetches a new access token using Refresh Token Flow from the commercetools platform API.

Argument

  1. token (String): refresh_token obtained from previous authorization process
  2. config (Object): Optional configuration which can override config properties given when building authClient object.

Usage example

await authClient.refreshTokenFlow('refreshToken')
// {
//      "access_token": "...",
//      "token_type": "Bearer",
//   "expires_in": 172800,
//      "expires_at": 1542287072875,
//      "scope": "manage_project:{projectKey}",
// }

Anonymous Session Flow

Fetches access token using Anonymous Session Flow from the commercetools platform API.

Argument

  1. anonymousId (Number): Id parameter which will be associated with generated access token. If not provided, API will autogenerate its own id.
  2. config (Object): Optional configuration which can override config properties given when building authClient object.

Usage example

await authClient.anonymousFlow(1)
// {
//      "access_token": "...",
//      "expires_in": 172800,
//      "expires_at": 1542287072875,
//      "scope": "manage_project:{projectKey}",
//      "refresh_token": "...",
//      "token_type": "Bearer"
// }

Custom Flow

Runs a custom request based on given configuration.

Argument

  1. host (String): the host of the OAuth API service
  2. uri (String): path to login endpoint
  3. credentials (Object): Optional object containing username and password for password authentication
  4. body (String): request body formatted as application/x-www-form-urlencoded content type, see example here.
  5. authType (String): Auth type performed in the auth request (default Basic).
  6. token (String): A token which will be sent in Authorization header. If not provided, we calculate it from credentials.
  7. headers (Object): Optional object containing headers which should be sent in auth request.

Usage example

await authClient.customFlow({
  host: 'https://custom.url',
  uri: '/login',
  body: JSON.stringify({
    username: 'username',
    password: 'password',
  }),
  headers: {
    'Content-Type': 'application/json',
  },
})
// {
//      ...API response
// }

Token Introspection

Fetches info about access_token using Token Introspection from the commercetools platform API.

Argument

  1. token (Number): access token which should be introspected.
  2. config (Object): Optional configuration which can override config properties given when building authClient object.

Usage example

await authClient.introspectToken('valid_token')
// {
//      "active": true,
//      "scope": "manage_project:{projectKey}",
//      "exp": 1539430105805
// }

await authClient.introspectToken('invalid_token')
// {
//   "active":false
// }

Token Provider

Token provider is a special class which watches over access_token and refreshes it using sdkAuth.refreshTokenFlow() method if it is expired.

Constructor argument

  1. options (Object): Configuration object
    • sdkAuth - SdkAuth object initialized with project credentials
    • fetchTokenInfo - Optional function which will be called for retrieving access_token if the tokenInfo or refresh_token were not provided.
    • onTokenInfoChanged - Optional function which is being called when the tokenInfo gets changed (manually or by refresh process)
    • onTokenInfoRefreshed - Optional function which is being called when the tokenInfo gets refreshed
  2. tokenInfo (Object): Optional parameter containing token information loaded from one of auth flows ({ access_token, refresh_token, expires_at })

Usage example

Minimal example:

import SdkAuth, { TokenProvider } from '@commercetools/sdk-auth'

// initiate TokenProvider
const tokenProvider = new TokenProvider({
  sdkAuth: new SdkAuth({
    // .. init SdkAuth
  }),
  fetchTokenInfo: (sdkAuth) => sdkAuth.clientCredentialsFlow(),
})

// get access token
const accessToken = await tokenProvider.getAccessToken()

// get whole tokenInfo object
const tokenInfo = await tokenProvider.getTokenInfo()

// invalidate current tokenInfo so the tokenProvider will use fetchTokenInfo fn to fetch new one
tokenProvider.invalidateTokenInfo()

Another example:

import SdkAuth, { TokenProvider } from '@commercetools/sdk-auth'

const authClient = new SdkAuth({
  // .. init SdkAuth
})

// get tokenInfo from authorization flow
const tokenInfo = await authClient.clientPasswordFlow({
  username: '...',
  password: '...',
})

// initiate TokenProvider
const tokenProvider = new TokenProvider(
  {
    sdkAuth,
    onTokenInfoChanged: (newTokenInfo) =>
      console.log('Token info was changed', newTokenInfo),
  },
  tokenInfo
)

// tokenInfo can be provided also later using "setTokenInfo()" function
// tokenProvider.setTokenInfo(tokenInfo)

// get currently used token info
// const usedTokenInfo = tokenProvider.getTokenInfo()

// check access_token validity, refresh if needed and return it
const accessToken = await tokenProvider.getAccessToken()

results matching ""

    No results matching ""