ghosteins ghosteins - 3 months ago 58
Javascript Question

How to get the code parameter in and oAuth process with Slack in node JS?

I'm trying to develop an app for slack.
I'm want to get the code parameter send in answer to the oauth flow with a slack button but I don't know how to get the parameter.

In fact I sent first the button then someone can click on it an implement the app on its slack channel then the oauth flow redirect me to a new webpage which url is
https://www.myappname.com/oauth/?code=[parameter I wan't to get]&state=

The problem is that my method to get the code parameter doesn't wait for the redirection.

Here is my code :



var app = express();
var router = express.Router();

var port = process.env.PORT || 5000;
app.use('/', router);

recupCode = function(req, res, next){
console.log(req.params);
console.log('cb1 : le code est récupéré');
res.end();
};

//Fonctions de Callback
boutonSlack = function(req, res) {
res.send('<a href="https://slack.com/oauth/authorize?scope=incoming-webhook,'
+'&client_id='+process.env.CLIENT_ID+'">'
+'<img alt="Add to Slack" height="40" width="139"'
+'src="https://platform.slack-edge.com/img/add_to_slack.png" '
+'srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, '
+'https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" /></a>');

console.log('cb0:le bouton slack s\'affiche');
router.get('/oauth/',recupCode);
};

router.get('/',boutonSlack);
app.listen(port, function () {
console.log('Ready');
});




Answer

You said you wanted to obtain the code - the access code is sent as a url parameter from Slack to your app in a GET request after the user clicks on your Add to Slack button and authorizes Slack's request to install your app. Your app waits for these requests from Slack in the router.get('/', function(request, response){};and you use request.url to access the string containing the code.

With some string manipulation you can extract the code value from the url and call Slack's auth.access(client_id, client_secret, code) in a request to exchange the code for your client's access_token. This access_token is what you use to do everything with a team, so you'll want to store it.

https://api.slack.com/methods/oauth.access

The button is usually displayed on a website and the node application acts as a server waiting for authorization requests coming from Slack.

https://api.slack.com/docs/slack-button

This is how I setup my index.js file in my node app to wait for installation requests. I don't use the router directly and I prefer the request library

const express = require('express');
const request = require('request'); //I prefer the request library to make requests 

var path_to_access_token = "https://slack.com/api/oauth.access?client_id=[INSERT_CLIENT_ID]&client_secret=[INSERT_CLIENT_SECRET]&code="; //Slack URL to call to receive accessToken
var app = express();

 /* WAIT FOR NEW APP INSTALLATION REQUESTS FROM SLACK */
app.get('/*', function(req, res) {
  // Tease out accessCode from the Slack request, if it exists 
  var url = req.url;
  var codePos = url.indexOf("code="); //index where code= starts in url
  var codeStartPos = codePos + 5; //Start of accessCode (+5 because code= is 5 characters)
  var endingPos = url.indexOf("&"); //End of accessCode, where another parameter starts
  var accessCode = url.substring(codeStartPos, endingPos).toString();   //Extract code from url

  // Verify user accepted Slack's auth request by looking for access_code existence
  if (codePos > -1) {    // User authorized oAuth request from Slack
    var completePath = path + accessCode; //Slack API call + code to receive accessToken and teamInfo
    request(completePath, function(error, response, body) { // Request token from Slack using the access_code, then handle response
      if(!error && response.statusCode == 200 && teamInfo.ok == true){
        var teamInfo = JSON.parse(body);   //Slack sends back access_code and team info in a JSON object
        //SAVE THE ACCESS_CODE
      } else {
        //ERROR
      }
     });
   } else {          //User denied auth request from Slack, so reroute back to signup page to start over
    //REROUTE USER BACK TO INSTALL PAGE, THEY DENIED AUTH REQUEST
   }
});