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

Signing in doesn't happen from the first time even if the username and the password are correct #184

Open
unste337 opened this issue Aug 1, 2024 · 23 comments
Labels
help wanted Extra attention is needed

Comments

@unste337
Copy link

unste337 commented Aug 1, 2024

Hi,

I am using the latest version of streamlit-authenticator (0.3.3) with the latest version of streamlit (1.37.0)

I am using the new multipage routing mechanism that streamlit recently released:
https://docs.streamlit.io/develop/concepts/multipage-apps/page-and-navigation

The issue is that I can't sign in from the first time. It doesn't seem to be doing anything when I do that. But the second time I sign in using the same username and password.

Here is a sample of the main file from which the authorization is done:

import yaml
from yaml import SafeLoader
import streamlit as st
import streamlit_authenticator as stauth

with open('config.yaml') as file:
    config = yaml.load(file, Loader=SafeLoader)

authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['preauthorized']
)

name, authentication_status, username = authenticator.login(max_concurrent_users=1)

if st.session_state['authentication_status']:
    authenticator.logout()
    st.write(f'Welcome *{st.session_state["name"]}*')
    st.title('Some content')
elif st.session_state['authentication_status'] is False:
    st.error('Username/password is incorrect')
elif st.session_state['authentication_status'] is None:
    st.warning('Please enter your username and password')

What can be the issue here? It works just fine eventually, but having to type a username and a password bothers some of my users

Thank you in advance!

@mkhorasani mkhorasani added the help wanted Extra attention is needed label Aug 1, 2024
@lasinludwig
Copy link

Same here. The first time i put the username and password into the login widget and login, nothing happens. If I put in the same credentials a second time, everything seems to work normally...

@mkhorasani
Copy link
Owner

mkhorasani commented Aug 4, 2024

Sure, will see to it that this is fixed. If you can please share a sample of your source code.

@lasinludwig
Copy link

Hi @mkhorasani

thanks for your quick response. You're welcome to look at my code, but I have to warn you: it's kind of a hot mess! 😁

I think the interesting bits are: the app starts with a login page which is where I create an instance of the Authenticate class and write it in the session state:

def s_add_once(key: str, value: AnyType) -> AnyType:
    """Add something to streamlit's session_state if it doesn't exist yet."""
    if key not in st.session_state:
        st.session_state[key] = value
        logger.info(f"st.session_state entry '{key}' added")
        return value

    logger.info(f"st.session_state entry '{key}' already exists")
    return st.session_state[key]

s_add_once is just a little helper function. I create the instance of Authenticate like this:

    authenticator: stauth.Authenticate = sf.s_add_once(
        "authenticator",
        stauth.Authenticate(
            credentials=uauth.format_user_credentials(),
            cookie_name="utec_tools",
            cookie_key="uauth",
            cookie_expiry_days=30.0,
        ),
    )

    name, auth, user = authenticator.login(
        fields={"Username": "Benutzername", "Password": "Passwort"}
    )
    logger.debug(f"\nAuthenticator: \nname: '{name}'\nstatus: '{auth}'\nuser: '{user}'")
    logger.debug(
        f"authentication_status in Session State: {sf.s_get('authentication_status')}"
    )

Every page starts by setting up a header with logo and title etc. In this header-setup function I get the authenticator instance from the session state and create an "unrendered" login form (if it's not the login page):

    if page != cont.ST_PAGES.login.short:
        authenticator: Any = st.session_state.get("authenticator")
        if not isinstance(authenticator, stauth.Authenticate):
            logger.critical("authenticator not initiated correctly")
            raise ValueError
        authenticator.login(location="unrendered")
        logger.debug("unrendered authenticator.login created")

With my logger messages I can see that after the first entry of the username and password, the variables "name", "auth", "user" and "authentication_status" in the session state are "None". After the second attempt, everything gets filled in correctly.

@lkdhy
Copy link

lkdhy commented Aug 6, 2024

Exactly the same problem here. I have been using and relying on the official multipage mechanism https://docs.streamlit.io/develop/concepts/multipage-apps/page-and-navigation. Really awaiting for the upcoming new version. ❤

@sidneijunior7
Copy link

sidneijunior7 commented Aug 20, 2024

Same problem here and no ideia what to do. In my case works after the first attempt and clearing caches.

@mkhorasani
Copy link
Owner

mkhorasani commented Aug 21, 2024

Fix is on the way! Should be released 2-3 weeks from now.

@lkdhy
Copy link

lkdhy commented Sep 15, 2024

Fix is on the way! Should be released 2-3 weeks from now.

Is the new release coming? My mentor got kind of annoyed when logging in twice 😭🤣.

Really appreciate this project ❤️.

@dataflo-w
Copy link

I had the same issue. I'm really looking forward to getting a fix in the upcoming version - for the time being, I downgraded to 0.3.1 and in my case, it works. Of course, this is only a quick fix if you are not dependent on updates/fixes of the newer versions.

@zizytd
Copy link

zizytd commented Sep 29, 2024

@mkhorasani
I see you are updating to version 0.3.4 currently, thank you for this, I appreciate it.

My questions are:

  • When will the new version be available for download as a pip package?
  • Does the new version solve the problem of logging in twice?
  • For the oauth2 authentication, I see it is just for guest users, is it possible that a normal user in the YAML file can log in via oauth authentication?

Thank you

@mkhorasani
Copy link
Owner

mkhorasani commented Sep 30, 2024

Dear all I just released the latest version, please try it. I have also created a new feature where you can provide the config file path to the Authenticate class instead of providing the credentials, cookie_name, cookie key, cookie_expiry_days, and pre_authorized parameters separately. If you choose to provide the path to the config file you will not need to resave the config file after using a widget, instead Streamlit-Authenticator will automatically take care of all read/update operations - I highly recommend using this feature as it will definitely eliminate the problem of the double login.

@mkhorasani
Copy link
Owner

mkhorasani commented Sep 30, 2024

@mkhorasani I see you are updating to version 0.3.4 currently, thank you for this, I appreciate it.

My questions are:

  • When will the new version be available for download as a pip package?
  • Does the new version solve the problem of logging in twice?
  • For the oauth2 authentication, I see it is just for guest users, is it possible that a normal user in the YAML file can log in via oauth authentication?

Thank you

You're welcome.

  1. Already released
  2. Yes please see previous comment
  3. Not with the same email/username, but with another email yes.

@Leon-Sander
Copy link

Leon-Sander commented Oct 1, 2024

@mkhorasani I am on streamlit-authenticator 0.4.1 and give the auth config path to the autheticator. The double login Error persists. Also for registration I needed 2 trys.
After logging out the login works on first try, but when freshly opening the application, the first login needs 2 trys.
Here is my setup, under the pages folder I got entrypoint.py, app.py and authentication.py
From the project root: streamlit run pages/entrypoint.py

entrypoint.py

import streamlit as st
pg = st.navigation([st.Page("authentication.py"), st.Page("app.py")])
pg.run()

authentication.py

import streamlit as st
import streamlit_authenticator as stauth

CONFIG_FILENAME = 'auth_config.yaml'


#with open(CONFIG_FILENAME) as file:
#    config = yaml.load(file, Loader=SafeLoader)

st.header('Account page')


authenticator = stauth.Authenticate(CONFIG_FILENAME)

login_tab, register_tab = st.tabs(['Login', 'Register'])

with login_tab:
    authenticator.login(location='main')

    if st.session_state["authentication_status"]:
        st.session_state.authenticator_object = authenticator
        #st.switch_page('app.py')
        authenticator.logout(location='main')    
        st.write(f'Welcome *{st.session_state["name"]}*')

    elif st.session_state["authentication_status"] is False:
        st.error('Username/password is incorrect')
    elif st.session_state["authentication_status"] is None:
        st.warning('Please enter your username and password')

with register_tab:
    #It is 8-20 characters, one lowercase letter, one uppercase, one number AND one special character (@$!%*?&)
    if not st.session_state["authentication_status"]:
        try:
            #config['pre-authorized']["emails"]
            email_of_registered_user, username_of_registered_user, name_of_registered_user = authenticator.register_user(pre_authorized=["[email protected]"])
            if email_of_registered_user:
                st.success('User registered successfully')
        except Exception as e:
            st.error(e)

app.py

print("hello world")

@mkhorasani
Copy link
Owner

@mkhorasani I am on streamlit-authenticator 0.4.1 and give the auth config path to the autheticator. The double login Error persists. Also for registration I needed 2 trys. After logging out the login works on first try, but when freshly opening the application, the first login needs 2 trys. Here is my setup, under the pages folder I got entrypoint.py, app.py and authentication.py From the project root: streamlit run pages/entrypoint.py

entrypoint.py

import streamlit as st
pg = st.navigation([st.Page("authentication.py"), st.Page("app.py")])
pg.run()

authentication.py

import streamlit as st
import streamlit_authenticator as stauth

CONFIG_FILENAME = 'auth_config.yaml'


#with open(CONFIG_FILENAME) as file:
#    config = yaml.load(file, Loader=SafeLoader)

st.header('Account page')


authenticator = stauth.Authenticate(CONFIG_FILENAME)

login_tab, register_tab = st.tabs(['Login', 'Register'])

with login_tab:
    authenticator.login(location='main')

    if st.session_state["authentication_status"]:
        st.session_state.authenticator_object = authenticator
        #st.switch_page('app.py')
        authenticator.logout(location='main')    
        st.write(f'Welcome *{st.session_state["name"]}*')

    elif st.session_state["authentication_status"] is False:
        st.error('Username/password is incorrect')
    elif st.session_state["authentication_status"] is None:
        st.warning('Please enter your username and password')

with register_tab:
    #It is 8-20 characters, one lowercase letter, one uppercase, one number AND one special character (@$!%*?&)
    if not st.session_state["authentication_status"]:
        try:
            #config['pre-authorized']["emails"]
            email_of_registered_user, username_of_registered_user, name_of_registered_user = authenticator.register_user(pre_authorized=["[email protected]"])
            if email_of_registered_user:
                st.success('User registered successfully')
        except Exception as e:
            st.error(e)

app.py

print("hello world")

Hi @Leon-Sander, I am unable to recreate this error. Can you please try using it without providing the path?

@Leon-Sander
Copy link

Hi @mkhorasani, I had the error without providing the path, then switched to providing it, the error occurs on both ways

@mkhorasani
Copy link
Owner

Hi @mkhorasani, I had the error without providing the path, then switched to providing it, the error occurs on both ways

Are you using Streamlit 1.37.0? That's the version I'm using.

@Leon-Sander
Copy link

I was using 1.38.0, I just checked with 1.37.0, no difference. Also checked multiple browsers just in case.

@Leon-Sander
Copy link

I created a test repository so everyone in this thread can check: https://github.com/Leon-Sander/Streamlit-Authenticator-Test

@zizytd
Copy link

zizytd commented Oct 1, 2024

@mkhorasani
I just checked the new version. I tried with both the path and without the path, but the login twice error persists, as @Leon-Sander mentioned.
I tried with both Streamlit 1.37 and 1.38.

@mkhorasani
Copy link
Owner

@mkhorasani I just checked the new version. I tried with both the path and without the path, but the login twice error persists, as @Leon-Sander mentioned. I tried with both Streamlit 1.37 and 1.38.

That's unusual because I am unable to recreate this issue locally. I will investigate further.

@Leon-Sander
Copy link

What I noticed is that you dont even need to enter something the first time. Just clicking login with empty username and password will also just reset the UI, no warning about needing to enter username or something.

@zizytd
Copy link

zizytd commented Oct 2, 2024

What I noticed is that you dont even need to enter something the first time. Just clicking login with empty username and password will also just reset the UI, no warning about needing to enter username or something.

@Leon-Sander I guess why this behavior, is because in the first Login click the authentication_status = None even if you enter the password or not.

I'm trying to figure out why this specific issue doesn't occur in version 0.3.1 but occurs in newer versions. The only significant difference I've found is how the login logic is structured. In 0.3.1, it's all in one file, while newer versions split it across multiple modules. However, I doubt this is the cause of the issue.

@hongan1998611
Copy link

@unste337
You should add this code after you finish logging in.
if authentication_status: if 'rerun' not in st.session_state: st.session_state['rerun'] = True st.rerun()

@ai4ki
Copy link

ai4ki commented Nov 12, 2024

I guess the problem is with streamlit's multipage app handling. For a different reason, I updated from streamlit-1.37.1 to streamlit-1.40.0 yesterday and now the problem is gone. Can't explain why though...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

10 participants