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)
host
(String): the host of the OAuth API serviceprojectKey
(String): the key of the project to assign the default scope to (optional).authType
(String): Auth type performed in the auth request (defaultBasic
).token
(String): Atoken
which will be sent inAuthorization
header. If not provided, we calculate it from credentials.disableRefreshToken
(boolean): whether the API should generate a refresh tokencredentials
(Object): the client credentials for authentication (clientId
,clientSecret
)scopes
(Array): a list of scopes (defaultmanage_project:{projectKey}
) to assign to the OAuth tokenfetch
(Function): Afetch
implementation which can be e.g.node-fetch
orunfetch
but also the native browserfetch
function. Only needs be be passed if not globally available (e.g. throughisomorphic-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
config
(Object): Optional configuration which can override config properties given when buildingauthClient
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
credentials
(Object): Object with named arguments containing user credentialsusername
(String): customer emailpassword
(String): customer password
config
(Object): Optional configuration which can override config properties given when buildingauthClient
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
credentials
(Object): Object with named arguments containing user credentialsusername
(String): client emailpassword
(String): client password
config
(Object): Optional configuration which can override config properties given when buildingauthClient
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
token
(String):refresh_token
obtained from previous authorization processconfig
(Object): Optional configuration which can override config properties given when buildingauthClient
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
anonymousId
(Number): Id parameter which will be associated with generated access token. If not provided, API will autogenerate its own id.config
(Object): Optional configuration which can override config properties given when buildingauthClient
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
host
(String): the host of the OAuth API serviceuri
(String): path to login endpointcredentials
(Object): Optional object containing username and password for password authenticationbody
(String): request body formatted asapplication/x-www-form-urlencoded
content type, see example here.authType
(String): Auth type performed in the auth request (defaultBasic
).token
(String): Atoken
which will be sent inAuthorization
header. If not provided, we calculate it from credentials.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
token
(Number): access token which should be introspected.config
(Object): Optional configuration which can override config properties given when buildingauthClient
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
options
(Object): Configuration objectsdkAuth
- SdkAuth object initialized with project credentialsfetchTokenInfo
- Optional function which will be called for retrievingaccess_token
if thetokenInfo
orrefresh_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
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()