pythonauthenticationdiscordoauthflet

on_login function not getting executed in flet auth


I am trying to create a login using discord oauth in flet.but the on_login function is not getting executed my imports:

import os

import flet
from flet import ElevatedButton, Page
from flet.auth import OAuthProvider

my code:


def main(page: Page):
    provider = OAuthProvider(
        client_id=os.getenv("DISCORD_CLIENT_ID"),
        client_secret=os.getenv("DISCORD_CLIENT_SECRET"),
        authorization_endpoint="https://discord.com/oauth2/authorize",
        token_endpoint="https://discord.com/api/oauth2/token",
        scopes=['identify','guilds','email','guilds.join','guilds.members.read'],
        redirect_url="http://localhost:2000/api/auth/discord/redirect",
    )

    def login_click(e):
        page.login(provider)
        print('hello')

    def on_login(e):
        page.add(flet.Text('on_logi called')) 
        print('on_logi called', flush=True)
        if e.error:
            page.add(ElevatedButton(f"Login error: {e.error}"))
            return
        page.add(ElevatedButton(f"User ID: {page.auth.user.id}"))
        page.add(ElevatedButton(f"Access token: {page.auth.token.access_token}"))
        page.add(flet.Text('HELLOO DID IT WORK?'))

    page.on_login = on_login
    page.add(ElevatedButton("Login with Discord", on_click=login_click))

flet.app(main, port=2000, view=flet.WEB_BROWSER)

i do get the login with discord button and when i click it i got authorized and redirected but the on_login function did not get executed

my redirect URL set on discord: Discord redirect URL set

after authorizing the link got displayed on address bar:

http://localhost:2000/api/auth/discord/redirect?code=dBeM7yHjFSjgSC7h4LKrGBWAqDM54T&state=FTSgwNYUPC6w-zjTZ9EN4Q

i got no errors on the console tab and network tab and tried using different browser [Microsoft Edge and Google Chrome]


Solution

  • In flet 0.21.0, because of migration to fast Api on web server, Oauth handler URL Endpoint changed from /api/oauth/redirect to /oauth_callback

    if you want to use different Oauth callback endpoint you can use FLET_OAUTH_CALLBACK_HANDLER_ENDPOINT env var to customize.

    From discussions in github