Stack Exchange
Flask - 404 Error when redirected in Discord OAuth
I'm making a Discord OAuth2 app in Python Flask, using the code below:
main.py:
from flask import Flask,request, render_template,redirect,session
from oauth import Oauth

app = Flask(__name__)





@app.route("/", methods = ["get"])
def index():
    return redirect(Oauth.discord_login_url)


def get_random_string(length):
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(length))



@app.route("/login", methods = ["get"])
def login():
    code = request.args.get("code")
    access_token = Oauth.get_access_token(code)
    user_json = Oauth.get_user_json(access_token)

    return user_json.get("username")

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

oauth.py:
import requests

class Oauth(object):
    client_id = "myid"
    client_secret = "mysecret"
    scope = "identify%20email"
    redirect_uri = "https://example.com/login"
    discord_login_url = "https://discord.com/api/oauth2/authorize?client_id={}&redirect_uri={}&response_type=code&scope={}".format(client_id, redirect_uri, scope)
    discord_token_url = "https://discord.com/api/oauth2/token"
    discord_api_url = "https://discord.com/api"


    @staticmethod
    def get_access_token(code):
        payload = {
            'client_id': Oauth.client_id,
            'client_secret': Oauth.client_secret,
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': Oauth.redirect_uri,
            'scope': Oauth.scope
        }

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }


        access_token = requests.post(Oauth.discord_token_url, data=payload, headers=headers)
        json = access_token.json()
        return json.get("access_token")


    @staticmethod
    def get_user_json(access_token):
        url = Oauth.discord_api_url + "/users/@me"

        headers = {
            "Authorization": "Bearer {}".format(access_token)
        }

        user_object = requests.get(url=url, headers=headers)
        user_json = user_object.json()
        return user_json


I tested that on my PC with the redirect set to localhost:5000/login and it worked, but I tried it on my Ubuntu VPS and changed the redirect to oauth.yankue.com:5000/login, but when i got sent to oauth.yankue.com:5000/login it displayed a 404 error, saying The requested URL was not found on this server.. I'm really unsure what the issue is. This is being stored in my var/www/html, i don't know if that makes a difference that it's amongst all the normal webpages on my apache server? Thanks for helping!


I tested that on my PC with the redirect set to localhost:5000/login and it worked, but I tried it on my Ubuntu VPS and changed the redirect to oauth.yankue.com:5000/login,

that's probably because you didn't configure oauth.yenkue.com subdomain for your Flask app when you moved it to the VPS. I recommend you refactoring your code using blueprints for scalability and ease of maintenance, refer to :

https://flask.palletsprojects.com/en/1.1.x/api/?highlight=subdomain#flask.Flask.register_blueprint

and i would also recommend you this package: https://pypi.org/project/discord.py/
and below how i managed to solve your issue (blueprint and subdomain parts) then you should adapt it your need:
git repo https://github.com/cizario/yenkue
.yankue.com

  .. venv/

  .. yenkue/


    .. errors/  # Blueprint
      .. __ init__.py
      .. views.py

    .. home/  # Blueprint
      .. __ init__.py
      .. views.py

    .. oauth/  # Blueprint
      .. __ init__.py
      .. discord.py  # your OAuth class goes here (just renamed for consistency ..)
      .. views.py


    .. __ init__.py

    .. app.py

  .. wsgi.py

yenkue/app.py
from flask import Flask


def create_app():
    """Create a Flask application using the app factory pattern."""

    app = Flask(__name__)
    app.config['SERVER_NAME'] = 'yankue.com'  # Important

    """Register blueprints."""
    from .errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from .oauth import bp as oauth_bp
    app.register_blueprint(oauth_bp, subdomain='oauth')  # set the subdomain

    from .home import bp as home_bp
    app.register_blueprint(home_bp)
    
    return app

yenkue/home/views.py
from flask import Blueprint, jsonify, redirect, url_for

bp = Blueprint('home', __name__)

@bp.route('/')
def index():
    # return jsonify(message="home index")
    return redirect(url_for('oauth.login'))

yenkue/home/__ init__.py
from .views import bp

in oauth blueprint, put all related authentication functions : login ..
yenkue/oauth/views.py
from flask import Blueprint, jsonify

bp = Blueprint('oauth', __name__)

@bp.route('/login')
def login():

    # put your logic here ..

    return jsonify(message="OAuth login page")
    

yenkue/oauth/__ init__.py
from .views import bp

