Skip to content

Instantly share code, notes, and snippets.

@JSpiner
Last active November 12, 2023 10:40
Show Gist options
  • Save JSpiner/c518a2b5415bc292406d3cb744833105 to your computer and use it in GitHub Desktop.
Save JSpiner/c518a2b5415bc292406d3cb744833105 to your computer and use it in GitHub Desktop.
Slack OAuth 인증방법

Slack OAuth 인증방법

Slack APP 생성

https://api.slack.com/apps?new_app=1 에서 새로운 앱 생성

Basic Information 탭에서 ClientID와 Client Secret 메모

Event Subscriptions 설정

https://api.slack.com/apps/[앱아이디]/event-subscriptions

Event Subscription 탭에서 Request URL에 응답받을 주소를 넣는다.(HTTPS방식만 가능)

첫 인증시 HTTP-POST 방식으로 아래와 같은 json이 날아온다.

{
    "token": "Jhj5dZrVaK7ZwHHjRyZWjbDl",
    "challenge": "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P",
    "type": "url_verification"
}

입력받은 challenge를 그대로 json 형태혹은 raw로 리턴해주면 된다.

HTTP 200 OK
Content-type: application/x-www-form-urlencoded
{"challenge":"3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P"}

flask code

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route('/slack')
def slack():
    payload = request.get_data()
    data = json.loads(payload)
    return Response(data["challenge"], mimetype='application/x-www-form-urlencoded')

app.run(host='0.0.0.0', debug='True')

https://서버주소/slack 을 통해 성공적으로 인증받을 수 있다.

인증받은 후 Team Events에 필요한 권한을 넣으면 된다.

OAuth 인증

OAuth & Permissions탭에서 OAuth 인증을 받을 링크를 추가한다.

ex) https://서버주소/oauth

팀 내에 우리가 만든 APP을 추가를 해야한다.

팀내에 APP 추가 링크 : https://slack.com/oauth/authorize?client_id=저장해논ID&scope=권한

scope는 channel:read+channel:history+team:read 식으로 권한+권한+권한 식으로 입력하면 된다.

위 링크를 통해 팀 내에 앱 추가 요청을 하면 https://서버주소/oauth 로 리다이렉트되면서

GET 방식으로 code가 날아온다.

이제 방금받은 code와 client_id client_secret를 같이 슬랙 서버로 보내면 인증절차가 끝난다.

flask code

from flask import Flask
from flask import Response
import requests

app = Flask(__name__)

@app.route('/slack', methods=['POST'])
def slack():
    payload = request.get_data()
    data = json.loads(payload)
    return Response(data["challenge"], mimetype='application/x-www-form-urlencoded')

@app.route('/oauth', methods=['POST'])
def oauth():
    code = request.args.get('code')
    r = requests.post("https://slack.com/api/oauth.access", data={'client_id':'아이디', 'client_secret':'시크릿', 'code':code, 'redirect_uri' : '선택사항'})
    response = json.loads(r.text)
    access_token = response['access_token']
    return 'auth success'

app.run(host='0.0.0.0', debug='True')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment