Last active
August 3, 2022 06:40
-
-
Save guillegette/fa7224724d1e08823b104d2afd9fc705 to your computer and use it in GitHub Desktop.
Implementing Slack Oauth 2.0 for www.workat.com
This file contains hidden or 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
const loginCallback = async (req, res, next) => { | |
const redirectUri = 'https://...'; // would be the URL defined above | |
const slackClient = await getSlackOpenIdClient(redirectUri); | |
const { slackLoginVerifyCode } = req.session; | |
const tokenSet = await slackClient.callback( | |
redirectUri, | |
req.query, | |
{ code_verifier: slackLoginVerifyCode } | |
); | |
const { access_token: accessToken } = tokenSet; | |
const { | |
'https://slack.com/team_id': teamId, | |
'https://slack.com/target_uri': targetUri, | |
'https://slack.com/user_id': slackUserId | |
} = tokenSet.claims(); | |
}; | |
This file contains hidden or 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
'use strict'; | |
const { Issuer, generators } = require('openid-client'); | |
const { | |
slackClientId, | |
slackClientSecret, | |
slackOpenIdIssuer | |
} = require('./config'); // your own configs | |
// Keep in memory to reduce calls | |
let issuer; | |
const getSlackOpenIdClient = async (callbackUri) => { | |
if (!issuer) { | |
issuer = await Issuer.discover(slackOpenIdIssuer); | |
} | |
return new issuer.Client({ | |
client_id: slackClientId, | |
client_secret: slackClientSecret, | |
redirect_uris: [callbackUri], | |
}); | |
}; | |
const login = async (req, res, next) => { | |
const { state } = req.query; | |
try { | |
// eslint-disable-next-line max-len | |
const callbackUri = 'https://..../callback'; // where slack will send the user back after authorization | |
const slackClient = await getSlackOpenIdClient(callbackUri); | |
// Generate code and save in session | |
const codeVerifier = generators.codeVerifier(); | |
req.session.slackLoginVerifyCode = codeVerifier; | |
const codeChallenge = generators.codeChallenge(codeVerifier); | |
const slackLoginUrl = slackClient.authorizationUrl({ | |
scope: LOGIN_SCOPES, | |
code_challenge: codeChallenge, | |
code_challenge_method: 'S256', | |
}); | |
return res.redirect(slackLoginUrl); | |
} catch (err) { | |
logger.error('Error during slack login', err); | |
return next(err); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment