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

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.)

Related

In Node.js using Express, restrict access to a route based on user credentials

In express app where users login using their web identities (google, facebook, amazon, etc) using passport.js for this. I have created a route. but only want that a single user should have access to it.
I have it working with extensive testing, but not entirely sure if its in fact secure enough?
Here is my code for the route:
app.get("/superSecretPage", function(req, res){
console.log(req.user);
if (req.isAuthenticated()){
if (req.user.userId === "XXXXXXXXXXXXXXXX") {
User.find({}, function(err, users){
res.render("userlist", {
users: users,
});
});
} else {
res.render("invalid")
}
} else {
res.redirect("login")
}
});
XXXXXXXXXXXXXXXX = being the users uniqueID from Google/Amazon/Facebook or another ID provider
Like i said this work, and only allows the user that equals req.user.userId, but is this secure enough?
This is not a proper way to do that. What will you do If you want to allow another user later? Will you open code and edit the user Id?
Do not hard code the user ID.
You need to implement Role Base Access Control. You need to create a super power user role and assign it to the users, Who you want to allow to access your super secret page. And use middlewares to check the role permissions.
This will help you : Role based auth | NodeJS
Like i said this work, and only allows the user that equals req.user.userId, but is this secure enough?
You haven't really shown enough to know about the overall security of this. The security depends upon at least the following:
Implementation of req.isAuthenticated()
How the user session was established and protected. Most sessions use a browser cookie to identify the session and it must be run over https to offer any protection. Then, you must also have proper auto-logout to make it less likely the session is just left active where someone else can use it on that computer.
How the req.user.userId got set in the first place. You don't show this so we really have no idea what is behind that and whether it's following good security practices or not.
If there is any persistent storage of the user session, then the security of that storage mechanism is relevant.
Presuming there's a login mechanism, are secure (hard to guess) credentials required? Are there anti-hacking protections in place to attempt to thwart credential guessing.
If you are 100% sure that req.user.userId is valid and that this connection belongs to the appropriate user for the userId, then this bit of code works fine. But, the devil is in the details of making sure that req.user.userId is appropriately connected to an authorized user and that's where the hard work is of making security work.
Add a field in the db schema and set it to an array which contains all the route that the user has access to. When authenticating loop through the array to see if he/she can access the route he/she is trying to.

How to login a user using firebase authentication

I'm currently using firebase-admin to create a web Dashboard with node.js as a backend which will have multiple users and those users have user specific data in my database, note that I need them to be able to delete or add stuff to the database as well, I've managed to add new users to Autentication using firebase.auth().createUser() programmatically, but how would one go about logging in a user, and then from there controlling which uid is logged in and displaying his data (giving him access to the correct data, obviously don't want him messing with someone elses data).
I know this might seem like a really newbie question, and it probably is, but firebase docs always get me confused for some reason. Any tips? I'd greatly appreciate.
Any questions don't hesitate.
To login a new user, try this:
firebase.auth().signInWithEmailAndPassword(email, password)
this returns a Firebase.Promise which you can use to track the operation progress. If successful, it will return the corresponding Firebase.User object.
From there, the logged-in user will also be available in the firebase.auth().currentUser property. You can then use the user's uid property as a key for his JSON branch on the database.

Firebase RememberMe functionality

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)

ReactJS - how to setup login pattern?

I'm sorry if this question is a bit vague, but I'm tackling this problem for the first time and any pointer would be useful.
I am building a web app using ReactJS and I need a login system - first page with two fields username / password and submit button. The server returns a token (1234) and this needs to be used in an auth header (Authorization: Bearer 1234) in order to access the protected area.
How should I handle the login and make the browser update itself with the new content available after login?
As the others have pointed out, it is a good idea to use React-Router.
I think you can use pattern like this: You get user inputs and send them via AJAX (with JQuery, Superagent, whatever you want). If the input is valid and user authenticated, the server sends back token with some user info, which can include his roles or permissions. Based on these received data, you can use React-Router to render other component, e.g. welcome page (by calling replaceState on React-Router history object - in flux action for example).
Additionally, you should save this token in a cookie or into a session/local storage (in order to be able to use it on every subsequent request), and the user info could be stored in a Flux store. After saving this user the store emits change event, which should lead to rerender of your root component with the user information you got.
Then, based on the new user roles or permissions in your store, you can have for example ES7 decorator on some of your components deciding, if it displays the actual component or not.
Hope it helps you a bit.

What's the best way to provide forgotten password functionality with CouchDB and Backbone.js?

I've got an ajax app built using backbone.js and it's hooked up to a couchdb instance. I am trying to build forgotten password functionality using the following workflow:
1) user enters their username
2) I send them an email with a link in it
3) the user accesses the link and enters a new password
I can't figure out how to actually get the password updated however. For security reasons, I'm not going to embed admin creds into the client, and it looks to me like a user has to be authenticated before they can make changes to their password.
Thank you for your time and assistance. Hopefully I'm just overlooking something silly.
I do it like this: save a unique key to DB, send a link that includes that key to visitor email and of course when he will access the link you will need to check the availability of that key, maybe consider 15 minutes since key was sent or decline his reset request

Categories