Search code examples
pythonflaskslackslack-api

Python slackclient oauth.access call returning 'invalid_code' error


I am using ngrok + flask + python slackclient to respond to Slack API's OAuth Flow and I am receiving an invalid_code error.

I am following steps described in slackclient docs and my code is pretty simple so far:

import os
import slack
from flask import Flask, request
app = Flask(__name__)

SLACK_CLIENT_ID = os.environ['SLACK_CLIENT_ID']
SLACK_CLIENT_SECRET = os.environ['SLACK_CLIENT_SECRET']

@app.route('/install', methods=['GET', 'POST'])
def install():
    # Retrieve the auth code from the request params
    auth_code = request.args['code']

    # An empty string is a valid token for this request
    client = slack.WebClient(token='')

    # Request the auth tokens from Slack
    response = client.oauth_access(
        client_id=SLACK_CLIENT_ID,
        client_secret=SLACK_CLIENT_SECRET,
        code=auth_code
    )

    print(response)

if __name__ == '__main__':
    app.run()

I initiate the App installation from the "Add" button in my Slack workspace's Manage Apps page. I can confirm that I am receiving a code as expected once the installation is initiated, and it is being correctly passed through to the slack.BaseClient.api_call() function that eventually sends the request to https://slack.com/api/oauth.access.

I expect the response from the oauth_access call to be a JSON object containing my access tokens, however, I get:

slack.errors.SlackApiError: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'invalid_code', 'warning': 'superfluous_charset', 'response_metadata': {'warnings': ['superfluous_charset']}}

I tried to send a POST with curl to Slack's endpoint with the required parameters and it worked as expected. I also tried with requests.post() and that also worked as expected. So I suspect that I am using slackclient incorrectly or have misunderstood something. Can anyone help point me in the right direction?


Solution

  • It seems to be a problem with the Python SDK. I think this pull request fixes this

    https://github.com/slackapi/python-slackclient/pull/527

    In the meantime it may be easier to revert to version 2.1.0