question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add OAuth support to bolt

See original GitHub issue

Description

Let’s add OAuth support to bolt!

It can use the new OAuth package we’ve been developing at https://github.com/slackapi/node-slack-sdk/pull/963.

The idea being, when you are initializing your app, by passing in a few new options, bolt would automatically setup a route for direct install and a route for oauth redirect. It would also take care of creating a state param for you and exchanging that + the code for an access token. Lastly, it will provide an interface to plug your own database solution to store and retrieve access tokens and other installation related info.

const app = new App({
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  clientId: process.env.SLACK_CLIENT_ID,
  clientSecret: process.env.SLACK_CLIENT_SECRET,
  stateSecret: 'my-state-secret',
  scopes: ['channels:read', 'groups:read', 'channels:manage', 'chat:write'],
  metadata: 'some_metadata',
});

What type of issue is this? (place an x in one of the [ ])

  • enhancement (feature request)

Requirements (place an x in each of the [ ])

  • I’ve read and understood the Contributing guidelines and have done my best effort to follow them.
  • I’ve read and agree to the Code of Conduct.
  • I’ve searched for any related issues and avoided creating a duplicate issue.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:3
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
realappiecommented, Aug 18, 2020

@stevengill Do you have a fully working example of this anywhere? I pretty much wrote everything in the documentation regarding oauth here. Without any success 😕 I have also tried the install link without any success. I also currently have a working setup with a custom express route, but would love to switch over to the built-in implementation.

My custom implementation This is perhaps useful to share for anyone that can't get the built-in implementation to work either.
export const createSlackAuthServer = (slackExpressReceiver: ExpressReceiver, slackApp: App, firestore: FirebaseFirestore.Firestore) => {

 const app_express = slackExpressReceiver.app;

 /* oauth callback function */
 app_express.get('/auth', async (req, res, next) => {

   const code: string = req.query['code'] as string;

   if (isNil(code)) {
     res.status(500).send('No code query param found');
   }

   try {
     const result = await slackApp.client.oauth.v2.access({
       client_id: config.slack.client_id,
       client_secret: config.slack.client_secret,
       code: code
     });

     const teamId: string = get(result, 'team.id') as string;

     const accessToken = get(result, 'access_token') as string;

     const authTestResponse: unknown = await slackApp.client.auth.test({
       token: accessToken
     });

     const authTestResponseTyped = authTestResponse as SlackAuthTestResponse;

     const installationDocument: SlackInstallationDocument = {
       botId: authTestResponseTyped.bot_id,
       teamId,
       botUserId: get(result, 'bot_user_id') as string,
       botToken: accessToken,
       user_id: authTestResponseTyped.user_id,
     };

     const installingUserId = get(result, 'authed_user.id') as string;

     const enterpriseId = get(result, 'enterprise.id') as string;

     if (enterpriseId) {
       installationDocument.enterprise_id = enterpriseId;
     }

     await firestore.collection('installations').doc(teamId).set(installationDocument);

     // Open up the conversation in slack upon success
     //
     res.redirect(`https://slack.com/app_redirect?app=${config.slack.app_id}`)

     await slackApp.client.chat.postMessage({
       token: accessToken,
       channel: installingUserId,
       text: '',
       blocks: [{
           "type": "section",
           "text": {
             "type": "mrkdwn",
             "text": `Hi there! Welcome to the bitrise bot. To start using this bot please set a bitrise access token first.`
           }
         },
         slackBlockCreator.generateSetBitriseTokenModalActionBlock()
       ]
     });

     console.error(`[slack-auth] installation successful for teamId="${teamId}" enterpriseId="${enterpriseId}"`);
   } catch (error) {
     console.error('[slack-auth] error calling client.oauth.v2.access', error);

     res.status(500).send('Error authenticating');
   }
 });
}

And wherever you’re creating a new slack App do the following

const slackExpressReceiver = new ExpressReceiver({
  signingSecret: config.slack.signing_secret,
  endpoints: '/events'
});


const slackApp = new App({
  receiver: slackExpressReceiver,
  authorize: async ({ teamId }) => {
    const documentSnapshot = await firestore.collection('installations').doc(teamId).get();

    if ( !documentSnapshot.exists ) {
      throw new Error(`no matching installations for team="${teamId}"`);
    } else {
      console.log(`[slackApp:authorize] matching installations found for teamId="${teamId}"`)
    }

    const installation = documentSnapshot.data() as SlackInstallationDocument;

    return installation;
  }
});

createSlackAuthServer(slackExpressReceiver, slackApp, firestore); 
Read more comments on GitHub >

github_iconTop Results From Across the Web

OAuth at Bolt | Bolt Help
Bolt leverages OAuth 2.0's authorization code grant flow to grant access tokens and refresh tokens on behalf of Bolt Account users.
Read more >
Build your first Slack Bolt App Pt 3: OAuth & Storing ... - YouTube
Code: https://github.com/horeaporutiu/ oauth -sample/tree/part3-authBolt JS Framework code: ...
Read more >
Bolt for Python - Slack Platform Developer Tools
Bolt for Python supports and will handle token rotation automatically so long as the built-in OAuth functionality is used. For more information about...
Read more >
Slack Bot with Bolt for JavaScript and OAuth 2.0 to share the ...
I made it to add an app with an Add to Slack Button using Bolt for Javascript. The Slack commands don't work yet,...
Read more >
Build Slack apps in a flash
And Bolt offers OAuth support, which handles the “Add to Slack” flow, making token storage and access for multi-team installations simpler.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found