Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SessionMiddleware for auth #849

Open
1 task done
xodiumx opened this issue Oct 29, 2024 · 3 comments
Open
1 task done

SessionMiddleware for auth #849

xodiumx opened this issue Oct 29, 2024 · 3 comments

Comments

@xodiumx
Copy link

xodiumx commented Oct 29, 2024

Checklist

  • There are no similar issues or pull requests for this yet.

Is your feature related to a problem? Please describe.

Hi, was working on a task and ran into an issue where my application initializes two sessions.

AuthenticationBackend class creates its own session in the init method:

class AuthenticationBackend:
    """Base class for implementing the Authentication into SQLAdmin.
    You need to inherit this class and override the methods:
    `login`, `logout` and `authenticate`.
    """

    def __init__(self, secret_key: str) -> None:
        from starlette.middleware.sessions import SessionMiddleware

        self.middlewares = [
            Middleware(SessionMiddleware, secret_key=secret_key),
        ]

But if I need a session also in my application I initialize, when starting the app

fastapi_app = FastAPI()
fastapi_app.add_middleware(SessionMiddleware, secret_key="some")

and then I can't use session object from AuthBackend

Describe the solution you would like.

I think it would be more transparent to pass this middleware to the AuthenticationBackend, for example like this:

# or middlewares: list[Middleware]
def __init__(self, session_middleware: Middleware) -> None:
    self.middlewares = [
        session_middleware,
    ]

and initialize this middleware on application startup:

session = Middleware(SessionMiddleware, secret_key="some-key")
fastapi_app = FastAPI(middleware=[session,])
admin = Admin(
    authentication_backend=AdminAuthBackend(session_middleware=session),
)

I hope this helps someone spend less time looking for the problem than it took me to find it 🥲

@aminalaee
Copy link
Owner

I think you can subclass AuthenticationBackend to modify this.
But adding middlewares to the init is also fine by me. We just have to make it optional and initialize it when no argument is passed.

@aminalaee
Copy link
Owner

Feel free to create a PR for it.

@xodiumx
Copy link
Author

xodiumx commented Nov 11, 2024

Hi, thanks for the feedback, I'll try to send a PR in a free time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants