LoginSignup
1
2

More than 5 years have passed since last update.

Node.jsでslackログイン

Last updated at Posted at 2018-02-12

node.jsでslackログインして、ユーザーの情報を取得して表示するところまでやる。
基本的にはこのドキュメントに沿っておこなう。備忘録。

Slack appをつくる

上記ドキュメントの Create your Slack app if you haven't alreadyCreate a Slack app nowからSlackアプリを作る。
ClientIDなどができてることを確認。
また、Redirect URIが必要なので、FeatureのPermissionのところからRedirect URLを設定する。
一旦、ローカルでやるので、http://localhost:3000/slack/auth/redirect とか入れておく。

slack loginボタンを設置する

/views/index.ejs のなかに、

<a href="https://slack.com/oauth/authorize?scope=identity.basic&client_id=your_client_id&state=testapp">
  <img src="https://api.slack.com/img/sign_in_with_slack.png" />
</a>

を設置する。
※ 確認のために、stateを追記している。
※ profile画像も取得したい場合は、scope=identity.basic, identity.avatarとするなどscopeを追加する。(必要に合わせてpersmissionも追加する必要があるかも)

返ってきたcodeを使って、access tokenや情報を取得するようにする

/routes/slack.js にslackログインのやり取りを書いていく。
npmのrequestを利用する。https://github.com/request/request

var request = require('request');

router.get('/auth/redirect', function(req, res, next) {
    let code = req.query.code;
    let state = req.query.state;

    if (typeof code !== 'undefined' && state == "testapp") {
        request.get('https://slack.com/api/oauth.access?client_id=' + your_client_id + '&client_secret=' + your_client_secret + '&code=' + code, function(err, response, body) {
            let result = JSON.parse(body);

            // これで結果が取得できる
            console.log('result: ', result);
            console.log('userName:', result.user.name);
        });
    }

});

あとは、取得したデータをDB格納したり、sessionを良い感じにしたりするとOK。

レポジトリはこちら。https://github.com/mazeltov7/SlackLoginTest

ログインセッション周りは、
- Express.js + Session + Sequelizeで簡易ログイン(SessionStore利用)
に書いてます。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2