Firebase RememberMe functionality - javascript

My webapp allows different users to login in different tabs/browsers on the same machine with different credentials (using signInWithEmailAndPassword). I achieve this by calling firebase.initializeApp(config, 'appName'+new Date().getTime()) for each login
When the user closes the tab or reloads (in window.onbeforeunload) I call .auth().signOut() to log him out.
I now want to add a RemeberMe functionality to my app page, that is a tickbox that if (and only if) ticked, will allow following logins from the same machine and username without giving the password even if the machine was for example restarted in the meantime.
How can that be achieved ?
what I am thinking about is (when remember me is on) to generate a token on the client stored in a cookie and maintain a table on the db which links tokens to passwords, there are two problems with this, first of all the password is saved as is on the db which is bad and second the password needs to be sent back to the client which is also bad.
any better options ?

Starting with Firebase JS 4.2.0 you can now specify session persistence. You can login different users in multiple tabs by calling:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
And when the window is closed, the session is cleared.
For more on this, check https://firebase.google.com/support/release-notes/js#4.2.0 and https://firebase.google.com/docs/auth/web/auth-state-persistence

Just add a rememberMe checkbox to your login form with a reference variable(for an exmaple remember) and use firebase setPersistence like this,
firebase.auth().setPersistence(this.remember.checked ? fireauth.Auth.Persistence.LOCAL : fireauth.Auth.Persistence.SESSION)
(here I have used javaScript for the example)

Related

How to build "Selectable Keep Login" function by Cookie/JWT

I'm using Node(axios,pinia)+Vue3 as frontEnd,and node(express,bcrypt,jsonwebtoken)+MongoDB as BackEnd to build a SPA web.
I use JWT for login authentication and save at localstorage.
Now it only can keep login.
Hoping have Selectable "Keep Login" function like some forum usually have.
(After closing browser/shotdown will need to login again.)
I don't use sessionStorage for this website user often open new tab.Some cross tab problem bother me and I thought cookie might got better solution.
I can imagine only "Always login"/"temp login" can be done likes. But with selectable I can't thought a simple way to apply it.
Like now I'm thought still use LocalStorage(LS) for Vue to run,but also have Session Cookie(as Cookie)(Not sure the name but the cookiewill be deleted when all webs closed).
Keep login need no change for me.If set to temp login, then the setting will be save to JWT,all front/back could know.
Use cache as signal for closing browser,if (temp login)&&(no cookie){clear LS}.
However I wonder the localStorage can be extract so the func will not safty enough? Then a school computer will be disaster
I'm new to cookie/session,and want to know any better way for safty/efficent. I will prevent XSS.
It would be wonderful to have your experienct/Idea!
Poor language and consult at here first,If any describe not clear/too detail please tell me,I will try to edit it, thanks!
The use of JWT is below:
BackEnd use bcrypt verify user password and response a JWT(with userID for db to find,also save to user login record DB) and other basic user info.
Some response data like JWT,basic userinfo will be save in localstorage to let Vue decide display login/admin/different page.
When user send a request(some login-action), JWT will also be send as BearToken to bo verified by backEnd that JWT was record in that user login record.
So JWT is the only security key,the user's login record should have same JWT.
Because it save in localstorage,user must logout!(Despite I can set some limit time.)

Firebase: How to always force a sign-in?

Working in Eclipse, & using the provided methods in Firebase' docs, I was able to setup logins for several providers such as Google and Facebook, using the redirect option. I basically click on a button for the provider on my web page, & it takes me to the login screen where I can enter a UID and password (e.g. Google sign-in)
However, once I authenticate properly with a valid account, and even if I sign-out, I get logged into the same account, without ever getting the screen prompting to log in. Where is this information persisted? Closing out Eclipse, or turning the computer off, does nothing to help, so I believe this is all being saved somewhere.
How do I "forget" previous attempts, so that I can see a provider's log in screen, each and every time?
You can use setCustomParameters on AuthProviders.
For example, in the case of Google: https://firebase.google.com/docs/reference/js/firebase.auth.GoogleAuthProvider#setCustomParameters
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({prompt: 'select_account'});
firebase.auth().signInWithPopup(provider);
This will not forget the previous attempt but it will prompt the user to select an existing account or a new one.

Executing code when a session ends in sails.js

Using sails.js, is there a way to run a function when a user session expires or is finished? Some configuration to do in config/session.js?
I know exists session.destroy, which you can set a function to execute when the session is destroyed, but I need it to be a global unique function for the application.
The idea would be writing in db table the state of a user as offline, when it's session ends.
Thanks.
If you're asking if there is a way to see if a user's session has expired -
Yes! It depends on how you're storing the server-side component of the session. Remember, traditional sessions require 2 pieces to work correctly - something on the client side (a cookie for example) and something on the server side to remember the user. In Sails the server-side piece is stored in the data store specified in the adapter portion of the Session Config File. You can query this data-store (even if it's the default Memory Store) and look for all users that have expired sessions.
Going deeper...
If you're asking if there is a specific method that gets called when a user session expires, then no, that's not the way sessions work. Sessions are a "hack" to make HTTP stateful. They aren't an active/live thing in the way that if they die we are notified. A session is just a record (likely a database) with a long code and a date. When the user visits your site, they give you a code from their cookie and you verify against the record in your session database. If the record matches and hasn't expired, HURRAY! you know who they are and they continue with their request. If the record doesn't match or has expired, BOO!, prompt them to log in again.
Really jumping to conclusions now...
I presume from the last sentence that you're looking to try to monitor whether someone is logged in to track "active" users. I would suggest that sessions are a poor metric of that. With sessions I can log in to your site and then leave. Depending on the length of your session expiration (24 hours or 30 days are typical values) I would be shown as logged in for that entire time. Is that a really helpful metric? I'm not using using your site but you're showing me as "logged in". Furthermore I could come back on another device (phone or another browser) and I would be forced to log back in. Now I have 2 or more sessions. Which one is correct?
If you're trying to gauge active usage I would either use Websockets (they would tell you exactly when someone is connected/disconnected to one of your pages - read more here) or just have a "heartbeat" - Each time a user visits one of your pages that visit is recorded as last seen at. This gives you a rough gauge as to who is actively on the site and who hasn't done anything in, say, over an hour.
You can do this by adding policy to all route
for example add sessionAuth.js to policy folder :
module.exports = function(req, res, next) {
// If you are not using passport then set your own logic
if (req.session.authenticated) {
return next();
}
// if you are using passport then
if(req.isAuthenticated()) {
return next();
}
//make your logic if session ends here
//** do some thing /
};
add this lines to config/policies.js :
module.exports.policies = {
'*': 'sessionAuth'
}

Disable multiple user login for web based application

I'm creating a web based application that requires people to register and login for access to certain pages.
I want to stop users from giving out their username/password to other people by denying access to more than one person using the same username at the
same time.
Don't know if its a great solution but you can keep a bit in users table and set it to 1 when user is logged in. And check it before login, if its set don't allow more logins by other users. On logout function unset this bit.
In spring security, we can able to manage user login like this,
<session-management>
<concurrency-control max-sessions="1"/>
</session-management>
So when the time user logged in, you will gonna set some session values, If one more user going to login using existing user logged in ID and password, before going to login condition, check those parameters in the back end. You can able to prevent user login from multiple times for the Same userLogin and Password.
You can use either database or distributed cache.
I prefer using database ( User_ID, SessionKey, LoginTime, Logout time)
After login, you have to record entry in database/cache with a unique session id. When login is attempted with same credentials, update existing entry with logout time and create new entry with recent login time
e.g. When you login with John,
the entry in table is like 'John','1020edf1','29-06-2015 00:10:00',null.
When second login comes after 10 minutes,
The entries in table will be like this
'John','1020edf1','29-06-2015 00:10:00','29-06-2015 00:20:00'
'John','10asdf21','29-06-2015 00:20:00','null'
Form your application, you can have reaper thread mechanism, which will remove inactive sessions if user tries to logout from the application.
Here session key is unique session id generated by application server.

how to detect authentication timeout from client script

I have an ASP.NET application that is using forms authentication with a timeout set to five minutes. On my page I have a button, that when clicked, makes an AJAX call to an operation that lives on the service named in my .svc file. How do I know, from the client javascipt that the application has timed out? Or, how can I detect this in the global.asax; maybe in the application_beginrequest?
If you're talking about the session timeout. When this occurs, the IHttpSessionState.IsNewSession property should be set to true.
If you're referring to the auth timeout, then you have to check the AuthenticationTicket for expiration.
A variation on your approach: have a separate client script that first checks for authentication expiration by requesting a special page/handler which returns JSON structure to indicate the authentication status of the current user. Only after knowing that the user is still active do you then run your main ajax action. It's one more request but keeps you from entangling the timeout logic with the main ajax logic. You can also use separately in a "warning, your session will time out in x minutes" popup.
See this question and my answer there for more details about how to set it up, but the key point is that if you don't want the check for expiration to extend the sliding expiration you have to configure the expiration page/handler as a separate virtual directory with forms authentication set with slidingExpiration=false.

Categories