Skip to main content

OAuthContext

OAuthContext is an interface to the authentication process of an application (i.e. obtaining an access token with which to make requests). The SDK currently supports the following OAuth 2.0 grant types:

  • A = Authorization Code Flow (AZN)
  • I = Implicit Flow
  • R = Resource Owner Password Credentials Flow (ROPC)
  • D = Device Flow
Function Parameters Async A I R D Return
OAuthContext config 🚫 OAuthContext
getConfig 🚫 config Object
isValidConfig 🚫 Boolean
authenticate 🚫 🚫 🚫 url String
login 🚫 🚫 🚫 🚫 url String
login username, password 🚫 🚫 🚫 Object
authorize 🚫 🚫 🚫 Object
pollTokenApi deviceCode 🚫 🚫 🚫 token Object
getToken params token Object
handleResponse options, tokenObj Object
introspectToken token Object
refreshToken token 🚫 token Object
userInfo token Object
revokeToken token, tokenType Object
logout path, token Redirect for Implicit Flow
isAuthenticated token Boolean
isToken token 🚫 Boolean
fetchToken 🚫 🚫 🚫 🚫 token Object
handleCallback 🚫 🚫 🚫

OAuthContext(config)

The constructor requires a config object as a parameter and returns an OAuthContext object.

Refer to Config for more information.

Sample code:
let config = {
    tenantUrl            : process.env.TENANT_URL,
    clientId             : process.env.CLIENT_ID,
    clientSecret         : process.env.CLIENT_SECRET,
    redirectUri          : process.env.REDIRECT_URI,
    responseType         : process.env.RESPONSE_TYPE,
    flowType             : process.env.FLOW_TYPE,
    scope                : process.env.SCOPE,
    registrationProfileId: process.env.REGISTRATION_PROFILE_ID
}

let authClient = OAuthContext(config);
let config = {
    tenantUrl            : 'xxxx',
    clientId             : 'xxxx',
    clientSecret         : 'xxxx',
    redirectUri          : 'http://localhost/authorize/callback',
    responseType         : 'xxxx',
    flowType             : 'authorization',
    scope                : 'openid',
    registrationProfileId: 'xxxx'
}

let authClient = OAuthContext(config);
let config = {
    tenantUrl            : 'xxxx',
    clientId             : 'xxxx',
    clientSecret         : 'xxxx',
    redirectUri          : 'http://localhost/authorize/callback',
    responseType         : 'xxxx',
    flowType             : 'authorization',
    scope                : 'openid',
    registrationProfileId: 'xxxx'
}

let authClient = OAuthContext(config);

getConfig()

Returns the config passed as the parameter for the constructor

Sample code:
console.log("Config: " + authClient.getConfig());
console.log("Config: " + authClient.getConfig());
console.log("Config: " + authClient.getConfig());

isValidConfig()

Returns if the current OAuthContext is configured correctly (boolean).

Sample code:
console.log("Config valid: " + authClient.isValidConfig());
console.log("Config valid: " + authClient.isValidConfig());
console.log("Config valid: " + authClient.isValidConfig());

authenticate()

Authorization Code Flow: Returns a URL used to authenticate with the tenant.

Sample code:
app.get('/login', (req, res) => {

    authClient.authenticate().then(url => {
        res.redirect(url);
    }).catch(error => {
        res.send(error);
    })
})
let url = authClient.authenticate();
window.location.replace(url);
let url = authClient.authenticate();
window.location.replace(url);

login()

Implicit Flow: Returns a URL used to authenticate with the tenant.

Sample code:
Not supported in Node.js
let url = authClient.login();
window.location.replace(url);
let url = authClient.login();
window.location.replace(url);

login(username, password)

ROPC Flow: Retrieves a token object using the given credentials.

Sample code:
app.get('/authorize/callback', (req, res) => {

    authClient.login(req.body.username, req.body.password).then(token => {
        // store the token in a way that it can be associated with the requester
        storeToken(token);
    }).catch(error => {
        console.log(error);
    })

    // redirect user to 'home'
    res.redirect('/home');
    
})
authClient.login(username, password).then(token => {
    // store the token in a way that it can be associated with the requester
    storeToken(token);
}).catch(error => {
    console.log(error);
})
authClient.login(username, password).then(token => {
    // store the token in a way that it can be associated with the requester
    storeToken(token);
}).catch(error => {
    console.log(error);
})

authorize()

Device Flow: Performs the code exchange with the tenant and returns an Object containing the device code, user code and verification URI. The device code can be used to poll for an access token.

Sample code:
authClient.authorize().then(response => {
    var deviceCode = response.response.device_code;
    authClient.pollTokenApi(deviceCode);
}).catch(error => {
    console.log(error);
})
authClient.authorize().then(response => {
    var deviceCode = response.response.device_code;
    authClient.pollTokenApi(deviceCode);
}).catch(error => {
    console.log(error);
})
authClient.authorize().then(response => {
    var deviceCode = response.response.device_code;
    authClient.pollTokenApi(deviceCode);
}).catch(error => {
    console.log(error);
})

pollTokenApi(deviceCode)

Polls the token endpoint of the authorization server to retrieve a token object.

Sample code:
authClient.pollTokenApi(deviceCode).then(token => {
    storeToken(token)
}).catch(error => {
    console.log(error);
})
authClient.pollTokenApi(deviceCode).then(token => {
    storeToken(token)
}).catch(error => {
    console.log(error);
})
authClient.pollTokenApi(deviceCode).then(token => {
    storeToken(token)
}).catch(error => {
    console.log(error);
})

getToken(params)

Performs the code exchange with the tenant and returns the user's token object. This function should be executed after the user has authenticated through the tenant on the callback url route.

Sample code:
app.get('/authorize/callback', (req, res) => {

    authClient.getToken(req.url).then(token => {
        // store the token in a way that it can be associated with the requester
        storeToken(token);
    }).catch(error => {
        console.log(error);
    })

    // redirect user to 'home'
    res.redirect('/home');
    
})
let url = window.location.pathname;

authClient.getToken(url).then(token => {
    // store the token in a way that it can be associated with the requester
    storeToken(token);
}).catch(error => {
    console.log(error);
})

window.location.replace('/home');
let url = window.location.pathname;

authClient.getToken(url).then(token => {
    // store the token in a way that it can be associated with the requester
    storeToken(token);
}).catch(error => {
    console.log(error);
})

window.location.replace('/home');
Sample response
{
  "access_token": "string",
  "id_token": "string",
  "grant_id": "string",
  "expires_in": 0,
  "token_type": "Bearer",
  "scope": "string",
  "refresh_token": "string" // if configured
}

handleResponse(options, tokenObj)

Makes a request using the given options and tokenObj, refreshing the access token if it is expired.

Sample code:
authClient.handleResponse(options, token).then(response => {
    console.log(response.response);
}).catch(error => {
    console.log(error);
})
Not supported in Vanilla JS
Not supported in React JS

introspectToken(token)

Returns information relating to the given token.

Sample code:
authClient.introspectToken(token).then(response => {
    console.log(response.response);
}).catch(error => {
    console.log(error);
})
authClient.introspectToken(token).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
})
authClient.introspectToken(token).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
})
Sample response
{
  "client_id": "string",
  "userType": "regular",
  "preferred_username": "string",
  "uniqueSecurityName": "string",
  "token_type": "access_token",
  "realmName": "string",
  "ext": {},
  "groupIds": [
    "string"
  ],
  "exp": 0,
  "iat": 0,
  "active": true,
  "scope": "string",
  "grant_type": "string",
  "sub": "string"
}

refreshToken(token)

Manually refreshes the given access token.

Not supported in Vanilla JS and React JS for Implicit Flow.

Sample code:
let newToken;

authClient.refreshToken(oldToken.refresh_token).then(token => {
    console.log(token.response);
    // update token in storage
    newToken = token.response;
}).catch(error => {
    console.log(error);
})
authClient.refreshToken(oldToken.refresh_token).then(token => {
    console.log(token.response);
    // update token in storage
    storeToken(token.response);
}).catch(error => {
    console.log(error);
})
authClient.refreshToken(oldToken.refresh_token).then(token => {
    console.log(token.response);
    // update token in storage
    storeToken(token.response);
}).catch(error => {
    console.log(error);
})
Sample Response
{
  "access_token": "string",
  "id_token": "string",
  "grant_id": "string",
  "expires_in": 0,
  "token_type": "Bearer",
  "scope": "string",
  "refresh_token": "string" // if configured
}

userinfo(token)

Returns the user information associated with the given token.

Sample code:
authClient.userinfo(token).then(response => {
    console.log(response.response);
}).catch(error => {
    console.log(error);
})
authClient.userinfo(token).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
})
authClient.userinfo(token).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
})

revokeToken(token, tokenType)

Revokes either the access_token or refresh_token.

Sample code:
let token = getRequestersToken(req);

// revoking the access_token
authClient.revokeToken(token, 'access_token').then(response => {

}).catch(error => {
    console.log(error);
})

// revoking the refresh_token
authClient.revokeToken(token, 'refresh_token').then(response => {

}).catch(error => {
    console.log(error);
})
let token = fetchToken();

// revoking the access_token
authClient.revokeToken(token, 'access_token').then(response => {

}).catch(error => {
    console.log(error);
})

// revoking the refresh_token
authClient.revokeToken(token, 'refresh_token').then(response => {

}).catch(error => {
    console.log(error);
})
let token = fetchToken();

// revoking the access_token
authClient.revokeToken(token, 'access_token').then(response => {

}).catch(error => {
    console.log(error);
})

// revoking the refresh_token
authClient.revokeToken(token, 'refresh_token').then(response => {

}).catch(error => {
    console.log(error);
})

logout(path, token)

Authorization Code Flow: Revokes the access token.

Implicit Flow: Revokes the access token, removes the token from sessionStorage and redirects the user to the given path (or '/' if not provided).

Sample code:
app.logout('/logout/', (req, res) => {
    
    // retrieve the requesters associated token
    let token = getRequestersToken(req);

    authClient.logout(token).then(response => {

    }).catch(error => {
        console.log(error);
    })

    // redirect user to site index
    res.redirect('/');

})
authClient.logout(token).then(response => {

}).catch(error => {
    console.log(error);
});
authClient.logout(token).then(response => {

}).catch(error => {
    console.log(error);
});

isAuthenticated(token)

Returns if the the given token is active (boolean).

Sample code:
authClient.isAuthenticated(token).then(response => {
    console.log("Active: " + response);
}).catch(error => {
    console.log(error);
});
authClient.isAuthenticated(token).then(response => {
    console.log("Active: " + response);
}).catch(error => {
    console.log(error);
});
authClient.isAuthenticated(token).then(response => {
    console.log("Active: " + response);
}).catch(error => {
    console.log(error);
});

isToken(token)

Returns if the given token is a valid token object (boolean).

Sample code:
console.log("Valid token: " + authClient.isToken(token));
console.log("Valid token: " + authClient.isToken(token));
console.log("Valid token: " + authClient.isToken(token));

fetchToken()

Returns the token from the session's storage.

Sample code:
Not supported in Node.js
let token = authClient.fetchToken();
let token = authClient.fetchToken();

handleCallback()

Stores token into sessionStorage.

Sample code:
Not supported in Node.js
if (window.location.pathname == '/authorize/callback') {
    authClient.handleCallback();
    window.location.replace('/');
}
if (window.location.pathname == '/authorize/callback') {
    authClient.handleCallback();
    window.location.replace('/');
}