Search code examples
pythonflaskdiscord

Log into website via Discord API and store session


I've just been having a ton of issues trying to figure out how to do this. I need to use the Discord API to log into a website I've built, store it in a session, and at some point be able to call the username for a database entry.

I know you need to pull the OAuth2 and such but even after reading the documentation I am very lost, and the tutorials I can find on this using Flask/Python are 2-3 years old, of which Discord has made a lot of changes. So far I have all my oAuth2 info from the Discord Developer Portal stored in a config.py. From there, I also have the OAuth2 link that will let me log in, and give me a token in return. This token shows up in the URL after logging in.

I have no idea how to store the Discord session and access that token in the code. Once I can do that, I think I can PROBABLY get the username since I believe it grants access to current user data.

If anyone could help me by explaining after someone logs in and redirects, how would they store it then pull it later.

Anything is helpful, and I'm sorry this is a very beginner question I just haven't used Discord API before.

All the best.

EDIT: Would something like this work? Like for example(this is going to be fake code)

-- Login happens, redirects to /auth  
@app.route('/auth')
def auth():
    if request.method == 'POST':  
        session = request.args.get(code)
print(auth())

Solution

  • When you click on the OAuth2 link and logs in through Discord, they are redirected back to your website with a code in the URL.Your server then exchanges this code for an access token by sending a POST request to Discord's token endpoint. Once you receive the access token, you'll want to store it securely. Typically, you would store it in a session on the server side.With the access token, you can make requests to the Discord API to fetch user data, including the username.