Try slack OAuth authentication with flask (Slack API V2)

Need for OAuth authentication

When creating a slack app, if you want to install it in only one workspace, you can manually install it from the app's ** settings page **. However, if you want to install the app personally or finally ** publish it in the Slack directory, you need to install it with OAuth authentication.

I think that the mechanism of OAuth authentication of slack is the same as the general one.

Implementation by flask

Necessary information

code

import os
import slack
from flask import Flask, request, make_response

client_id = os.environ["SLACK_CLIENT_ID"]
client_secret = os.environ["SLACK_CLIENT_SECRET"]
#Add the scope required by the app here.
oauth_scope = ",".join([
  "channels:history",
  "groups:history",
  "im:history",
  "mpim:history",
  "chat:write"
  ]) #os.environ["SLACK_BOT_SCOPE"]
uuids = []

app = Flask(__name__)

@app.route("/begin_auth", methods=["GET"])
def pre_install():
    """Create a link to jump to the OAuth authentication page of slack and display it."""
    from uuid import uuid4
    state_string = str(uuid4())
    uuids.append(state_string)
    return f'<a href="https://slack.com/oauth/v2/authorize?scope={ oauth_scope }&client_id={ client_id }&state={ state_string}">Add to Slack</a>'

@app.route("/finish_auth", methods=["GET", "POST"])
def post_install():
    """It is the processing of redirected access after authentication is completed."""
    auth_code = request.args['code']
    state_code = request.args['state']

    #state_401 if the codes do not match
    if not state_code in uuids:
        return make_response("", 401)
    else:
        uuids.remove(state_code)

    #To authenticate, create a client with a blank token.
    client = slack.WebClient(token="")

    #Request an authentication token.
    response = client.oauth_v2_access(
        client_id=client_id,
        client_secret=client_secret,
        code=auth_code
    )

    #Save the slack bot token in DB etc.
    SLACK_BOT_TOKEN = response['access_token']

    #Don't forget to tell your users success!
    return make_response("Authentication successful!!", 200)

app.run()

Redirect URL settings

ʻApp> Basic Information> OAuth & Permissions> Register http: // localhost: 5000 / finish_auth in Redirect URLs`.

Save with Save URLs

スクリーンショット 2020-03-31 14.17.13.png

access

Now you are ready Start flask and go to http: // localhost: 5000 / begin_auth. スクリーンショット 2020-03-31 14.21.57.png

Clicking on the link will ask you to authenticate with slack.

スクリーンショット 2020-03-31 14.24.42.png

Press Allow to move to the next screen and generate a token at that time. If the UUID4 for verification matches, remove it from the list and use the slackClient to get an access token.

スクリーンショット 2020-03-31 14.30.35.png

I didn't write it in this code, but let's save the obtained access token for the next use.

reference

slack API Japanese document Installing with OAuth

Recommended Posts

Try slack OAuth authentication with flask (Slack API V2)
Try using Dropbox API v2 with Go
Flow to complete Slack authentication with Flask (Python)
Hit the Twitter API after Oauth authentication with Django
Try to make RESTful API with MVC using Flask 1.0.2
API with Flask + uWSGI + Nginx
Qiita API Oauth with Django
Persist Flask API server with forever
[Python] Use Basic/Digest authentication with Flask
Basic authentication and Digest authentication with Flask
Sample to use after OAuth authentication of BOX API with Python
[Python] Quickly create an API with Flask
Flask can't be RESTful with azure API Apps
Incorporate JWT authentication into Python's Flask Web API
[AWS] Try tracing API Gateway + Lambda with X-Ray
[Python] Mention to multiple people with Slack API
Flask Basic authentication
[First API] Try to get Qiita articles with Python
Try drawing a social graph using Twitter API v2
Upload to a shared drive with Google Drive API V3