LoginSignup
2
0

Discord認証 (OAuth2)

Last updated at Posted at 2023-07-30

参考

をもとに手を動かしてみた。

Discordでアプリケーションの作成

無題.png

image.png

Client ID, Client Secretをメモ

  • 特にClient Secretは一度しか表示されないため注意

image.png

認証が終わったら飛ぶ先URL指定

image.png

今回は http://localhost:8080/afterlogin
を指定しました。

URL Generator

  • identify にチェック

image.png

URLは

https://discord.com/api/oauth2/authorize?client_id=クライアントID&redirect_uri=リダイレクト先&response_type=code&scope=identify
となっている。

codeの取得

  • 先ほどの https://discord.com/api/oauth2/authorize?client_id(略)のURLにアクセスし、code値を取得

image.png

tokenの取得のため、curl でアクセス

windowsのコマンドプロンプトにて以下

set clientid=0000000000000000000
set clientsecret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
set redirect_uri=http://localhost:8080/afterlogin
set code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

curl -X POST -H "Content-Type:application/x-www-form-urlencoded" -d "client_id=%clientid%&client_secret=%clientsecret%&grant_type=authorization_code&code=%code%&redirect_uri=%redirect_uri%" https://discordapp.com/api/oauth2/token

失敗例

image.png

成功例

image.png

  • 有効期限 "expires_in": 604800 の値は7日間。(604800 / 24 / 60 / 60 = 7)

token値でDiscordのユーザー情報の取得

set access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
curl -H "Authorization: Bearer %access_token%" https://discordapp.com/api/users/@me
  • 以下のような情報が取得できる。
{"id":"000000000000000000"
,"username":"xxxxxxxx"
,"avatar":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
,"discriminator":"0000"
,"public_flags":0
,"flags":0
,"banner":null
,"accent_color":null
,"global_name":"xxxxxxxx"
,"avatar_decoration":null
,"banner_color":null
,"mfa_enabled":false
,"locale":"ja"
,"premium_type":0}

認証の延長

set clientid=0000000000000000000
set clientsecret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
set refresh_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

curl -X POST -H "Content-Type:application/x-www-form-urlencoded" -d "client_id=%clientid%&client_secret=%clientsecret%&grant_type=refresh_token&refresh_token=%refresh_token%" https://discordapp.com/api/oauth2/token

新しいrefresh_tokenが発行される。
なお発行された後は、古いrefresh_tokenは使用できなくなるので注意。

2
0
1

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
2
0