Last active
September 26, 2023 15:43
-
-
Save pravinady/4c51dd21ce5903ed0b7bf2143e306ce6 to your computer and use it in GitHub Desktop.
add-custom-sessionID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Handler that will be called during the execution of a PostLogin flow. | |
* Generates a custom sessionID & adds it to the accessToken & idToken | |
* | |
* @param {Event} event - Details about the user and the context in which they are logging in. | |
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login. | |
*/ | |
const { v4: uuidv4 } = require('uuid'); | |
const SESSIONID_CLAIM_NAME = 'x-session-id'; | |
const PROTOCOL_PASSWORD_GRANT = "oauth2-password"; | |
const PROTOCOL_REFRESH_GRANT = "oauth2-refresh-token"; | |
exports.onExecutePostLogin = async (event, api) => { | |
let customSessionId = ""; | |
if (event.transaction.protocol === PROTOCOL_PASSWORD_GRANT) { | |
console.log("[compute-session-id] - ROPG flow - Adding SessionID claim to tokens"); | |
customSessionId = uuidv4(); | |
addSessionIDToTokens(customSessionId, api); | |
} | |
else if (event.transaction.protocol === PROTOCOL_REFRESH_GRANT) { | |
console.log("[compute-session-id] - Refresh Token flow"); | |
customSessionId = event.request.body.sessionID; | |
console.log(`sessionID is: ${customSessionId}`); | |
if (customSessionId) { | |
console.log("[compute-session-id] - Refresh Token flow - Adding SessionID claim to tokens"); | |
addSessionIDToTokens(customSessionId, api); | |
} | |
else { | |
console.log("[compute-session-id] - Refresh Token flow - Missing SessionID in request"); | |
return | |
} | |
} else { | |
console.log(`[compute-session-id] - Skipped adding sessionID claim`); | |
return | |
} | |
}; | |
function addSessionIDToTokens(customSessionId, api) { | |
api.idToken.setCustomClaim(SESSIONID_CLAIM_NAME, customSessionId); | |
api.accessToken.setCustomClaim(SESSIONID_CLAIM_NAME, customSessionId); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment