Flow to complete Slack authentication with Flask (Python)

I implemented Slack authentication in Flask. Generally, you can see it by looking at the official document, but there are some parts that are a little confusing when you want to acquire user information at the same time as authenticating, so I will leave it as a memorandum.

Premise

I wrote about the registration of the Slack app in detail last time. https://qiita.com/svfreerider/items/0e1fe74c70e2047f0ce9

Most are just the code in the official documentation below. https://slack.dev/python-slackclient/auth.html

Source code

auth.py


import functools
import pdb
import slack

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)

from app.db import (
    search_user, register_user, search_team, register_team, search_team_user, register_team_user
)

bp = Blueprint('auth', __name__, url_prefix='/auth')
client_id = 'XXXXXXXXXXXXXXX'
client_secret = 'XXXXXXXXXXXXXXX'
oauth_scope = 'channels:read,chat:write:bot,users:read,users:read.email'

Prepare ʻauth.pyto implement the authentication function. Define theclient_id and client_secretthat you got when you registered your Slack app. In addition to this, definescope`. scope specifies the range of permissions required of the user to create this app. It is also necessary to set it on the application side. Also, when applying, you must state the reason for "why you need this scope".

In my case, I created a bot and sent notifications from it, so I added channels: read and chat: write: bot to specify the channels. I also included ʻusers: read and ʻusers: read.email because I would like to have the user's personal information and email address later.

auth.py


@bp.route('/redirect', methods=['GET'])
def authorize():
    authorize_url = f"https://slack.com/oauth/authorize?scope={ oauth_scope }&client_id={ client_id }"

    return redirect(authorize_url)

If you do this, you will be redirected to the Slack authentication screen by going to / auth / redirect.

auth.py


@bp.route('/callback', methods=["GET", "POST"])
def callback():
    auth_code = request.args['code']
    client = slack.WebClient(token="")
    oauth_info = client.oauth_access(
        client_id=client_id,
        client_secret=client_secret,
        code=auth_code
    )

After callback, use the code at the end of the URL to get the user's information. User acquisition is done with ʻoauth_access`.

However, at this time, the user's name and e-mail address information have not been obtained yet. This time, we will call the user's detailed information separately using the acquired ʻoauth_token`.

auth.py


    access_token = oauth_info['access_token']
    client = slack.WebClient(token=access_token)
    user_id = oauth_info['user_id']
    response = client.users_info(user=user_id)

With ʻusers_info`, you can get all the information you want, such as the user's email address and name, as well as the icon image and time zone.

This is not limited to Flask, but I think that Python can be used as it is. I put Flask in just two weeks ago, but as a longtime Rails player, I can't find any literature at all.

From now on, I think that the number of cases of making apps with machine learning + Flask will surely increase, so I will share it as needed.

Recommended Posts

Flow to complete Slack authentication with Flask (Python)
[Python] Use Basic/Digest authentication with Flask
How to upload with Heroku, Flask, Python, Git (4)
Try slack OAuth authentication with flask (Slack API V2)
Sample to send slack notification with python lambda
[Python] Mention to multiple people with Slack API
Programming with Python Flask
How to upload with Heroku, Flask, Python, Git (Part 3)
How to upload with Heroku, Flask, Python, Git (Part 2)
Connect to BigQuery with Python
Post from Python to Slack
BASIC authentication with Python bottle
Connect to Wikipedia with Python
Switch python to 2.7 with alternatives
Write to csv with Python
Web application with Python + Flask ② ③
Web application with Python + Flask ④
Post to Slack in Python
Send experiment results (text and images) to slack with Python
Python: How to use async with
Link to get started with python
[Python] Write to csv file with Python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python
Output to csv file with Python
MP3 to WAV conversion with Python
To do tail recursion with Python2
Basic authentication and Digest authentication with Flask
How to get started with Python
What to do with PYTHON release?
Unable to install Python with pyenv
How to use FTP with Python
How to calculate date with python
Easily post to twitter with Python 3
I want to debug with Python
Application development with Docker + Python + Flask
I tried to summarize everyone's remarks on slack with wordcloud (Python)
Try to reproduce color film with Python
Try logging in to qiita with Python
Convert memo at once with Python 2to3
Fixed to easily realize multifunctional login / logout with Python / Flask using Auth0
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
Memo to ask for KPI with python
Two-dimensional saturated-unsaturated osmotic flow analysis with Python
Simple Slack API client made with Python
Output color characters to pretty with python
Passwordless authentication with RDS and IAM (Python)
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Send a message from Python to Slack
Output Python log to console with GAE
Page cache in Python + Flask with Flask-Caching
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Fractal to make and play with Python
Connect to MySQL with Python within Docker
How to work with BigQuery in Python
[Introduction to Python] Let's use foreach with Python
Log in to Slack using requests in Python
Single pixel camera to experience with Python
[Python] Introduction to CNN with Pytorch MNIST