Signing in doesn't happen from the first time even if the username and the password are correct
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!
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...
Sure, will see to it that this is fixed. If you can please share a sample of your source code.
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.
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. ❤
Same problem here and no ideia what to do. In my case works after the first attempt and clearing caches.
Fix is on the way! Should be released 2-3 weeks from now.
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 ❤️.
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.
@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
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 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.
- Already released
- Yes please see previous comment
- Not with the same email/username, but with another email yes.
@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 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.pyentrypoint.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?
Hi @mkhorasani, I had the error without providing the path, then switched to providing it, the error occurs on both ways
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.
I was using 1.38.0, I just checked with 1.37.0, no difference. Also checked multiple browsers just in case.
I created a test repository so everyone in this thread can check: https://github.com/Leon-Sander/Streamlit-Authenticator-Test
@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 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.
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.
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.
@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()
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...
Hi @mkhorasani,
Hi,
I’m new to streamlit and streamlit authenticaror. I posted this earlier today on streamlit.io discussion forum but maybe I should have posted it here. I’m trying to put some authentication into my app. I seem to always be getting None back in my code. I understand that it gives a None value when it first loads but for some reason even after I enter a username & password and click Login it returns None.
Just wondering if I’m doing something incorrect or if Streamlit 1.42 is incompatible with the Authenticator.login. Can you please let me know.
Here is my code:
import streamlit as st import streamlit_authenticator as stauth import yaml from yaml.loader import SafeLoader
Load credentials with open(‘./credentials.yml’) as file: config = yaml.load(file, SafeLoader)
Create an authentication object authenticator = stauth.Authenticate( config[‘credentials’], config[‘cookie’][‘name’], config[‘cookie’][‘key’], config[‘cookie’][‘expiry_days’] )
Add login widget result = authenticator.login(‘main’, ‘Login’) print(result) if result is None:
Handle the case when no login data is returned
st.error(“Login failed or no login attempt made.”) else: name, authentication_status, username = result
Handle authentication status
if authentication_status: st.write(f’Welcome {name}')
Your app code here
authenticator.logout(‘Logout’, ‘main’) elif authentication_status == False: st.error(‘Username/password is incorrect’) elif authentication_status == None: st.warning(‘Please enter your username and password’)
Here is my YAML sample_file: credentials: usernames: jsmith: email: [email protected] name: John Smith password: abc # To be replaced with hashed password ksmith: email: [email protected] name: Kelly Smith password: def # To be replaced with hashed password cookie: expiry_days: 0 key: some_signature_key name: some_cookie_name
Thanks.
Bug detail: Point 3: Creating a config file states that - "If you do not require re-authentication, you may set the number of days to expiry to 0" In authentication_view.py [line 369, 370, 371] - It is setting the auth cookie using self.cookie_controller.set_cookie() and then in the next life it checks if the config file is set and if the cookie is available to fire a st.rerun. In cookie_model.py:: set_cookie() [line 94] - The cookie is not set if the expiry days is 0.
Temporary workaround: In your config file set cookie: expiry_days: 1 Impact: You will have to delete cookies every time you want to test you login use case or wait for the cookie to expire.