Chainlit / chainlit

Build Conversational AI in minutes ⚡️
https://docs.chainlit.io
Apache License 2.0
6.1k stars 777 forks source link

How to Handle AccessToken Authentication in Copilot #756

Open lianghsun opened 4 months ago

lianghsun commented 4 months ago

When using Copilot, if I want to utilize an accessToken for authentication, how can I receive this token on the Python side? I've attempted using @cl.password_auth_callback, but it seems that's not the correct approach. Are there any examples I can refer to?

willydouhard commented 4 months ago

So with the copilot, authentication works a bit differently.

In the regular chainlit, the user goes through an authentication flow that triggers some callbacks such as @cl.password_auth_callback.

For the copilot, it does not make sense to put the user through an auth process since it is probably up to the host website to authenticate the user. That is why it is up to the host website to generate the accessToken and pass it directly to chainlit, by passing the callback auth mechanism.

lianghsun commented 4 months ago

Thanks for replying @willydouhard ! But how do I get accessToken in Chainlit side?

alirizasaral commented 4 months ago

Thanks for replying @willydouhard ! But how do I get accessToken in Chainlit side?

+1

lehic commented 4 months ago

@lianghsun The access token should be managed on your end. You can generate an access token for each user.

Here is an example:

an import jwt
from datetime import datetime, timedelta

CHAINLIT_AUTH_SECRET = "YOUR_CHAINLIT_AUTH_SECRET"

def create_jwt(identifier: str, metadata: dict) -> str:
    to_encode = {
      "identifier": identifier,
      "metadata": metadata,
      "exp": datetime.utcnow() + timedelta(minutes=60 * 24 * 15),  # 15 days
      }

    encoded_jwt = jwt.encode(to_encode, CHAINLIT_AUTH_SECRET, algorithm="HS256")
    return encoded_jwt

user_access_token = create_jwt("user-1", {"name": "John Doe"})

After that, when you load the Copilot from your page, you can attach the access_token that is linked to your user on the mountChainlitWidget. Like this:

        <script src="http://localhost:8000/copilot/index.js"></script>
        <script>
            window.mountChainlitWidget({
                chainlitServer: 'http://localhost:8000',
                accessToken: '<user_access_token>'
            });
        </script>

Replace with the user_access_token variable.

From your Chainlit app, you can access user information like this: user = cl.user_session.get("user")

ajosegun commented 1 week ago

Hi,

I am facing a similar error!!

Did you get it working?