Can I use html5 local storage for storing user authentication session information - angularjs

QUICK BACKGROUND:
I'm writing a Mongo/Express/Angular/Node SPA and using passport I have setup OAuth log in options to handle the user authentication / authorization.
With passport I am successfully maintaining session on the server, so all my XHR requests (that need it) are checking for a logged in user.
On log in the server puts the basic user session info into a cookie for the client to find on the authorization callback, I then am using angular-cookies' $CookieStore to access that cookie on the client save it to the rootscope and clear the cookie.
PROBLEM:
This is working perfectly except for any event where the user refreshes the browser, which causes my rootscope session to obviously get wiped.
So I was considering storing session information in the browser local storage (using store.js) then even on the initial load I could check for the session existing in the browser local storage and bypass the OAuth login if there was already a session.
Is it bad practice or is there some logistical/security problems with storing user session information in the browser local storage?
This app doesn't have any senstive data, sign up is free and logging in is really only there so I can track users and store data created in the application for each user. And the user session would never have a password (I only allow OAuth login no local option).

Instead of the localStorage, look at sessionStorage object: http://www.w3schools.com/html/html5_webstorage.asp
It works exactly like localStorage, but the whole sessionStorage object will be deleted when the browser window is closed - but will survive any page refreshes. It is an ideal place for storing session ids and alike.
But be warned that the sessionStorage is isolated within a browser tab - that means if your user choses to open a link in a new tab, the sessionStorage for that will be initialized empty.

Related

What is the correct way to implement authentication persistence in ReactJS

In my React project, I have implemented authentication using Firebase authentication. Upon signing in successfully, the user details get stored in a 'user' object in the localStorage, and remain stored until the user specifically logs out. It is the presence of this 'user' object which is used to check whether the person is authenticated or not, and then subsequently open protected routes.
However, this method leads to a problem that one might copy the user details from the localStorage, and then set them manually using the console. This would lead to that user being signed in without authentication using their password.
So what is the correct and secure method to implement persistence of authentication in React
Like user object, any sensitive information should NOT be stored in localStorage, and the better option is to use HTTP only cookie.
This post answers your question and why you should use HTTP only cookie over localStorage:
https://stackoverflow.com/a/37396572/15881471
When used with the HttpOnly cookie flag, cookies are not accessible through JavaScript and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS

Hiding Routes in React Header based on Express.js User login status

I have an application that uses express.js as the server side language and React on the front-end. I use passport.js to authenticate routes in the server, using local login and facebook strategies (no JWT). I use express-session to manage the session, which seems straight forward ( or insufficient, which I do not know yet, for my case, as its work in progress ).
My requirement is to hide/show few links in the Header component.
i.e.,
Log In
Sign Up
should show up in index page, when user has not logged in, but hidden when he is logged in. Likewise, few links should be hidden when the user is not yet logged in.
What is the best wat to check this from the client? Making an AJAX call is not ideal, as I may have more use cases of checking if the user session is valid from the client.
I can see the default connect.sid cookie, which the express creates, but how do I make use of it, or is there a best way for the client to know that the user is already logged in.
You have a couple options. Here are some:
You can check for the presence of a different cookie in the browser, and use that as your metric for whether or not you are "logged in". Your browser won't know if the session has expired server side, so you still have to account for the fact that you may be logged out and not know it. Additionally, you have to be sure to clear this cookie when logging out and set it when logging in.
When starting, your browser can make a AJAX request to get the currently logged in user. This might be useful for all sorts of things, such as displaying the user's name when logged in. You really only need to do this once (on page load and on login), then keep track of the user's login state stored in memory. You mentioned you don't want to do this, but it is fairly common.
When loading the page, you can inject the user into the page. For example, when the page loads there will be a <script> tag containing window.currentUser = null or an object representing the user. You can use this to "bootstrap" the login state without needing an AJAX request.
To clarify, you can't use the connect.sid cookie by itself because this cookie is just the ID of the session, not the session data itself. Only the server knows the session data that's being stored for that user, not the client. You need some way aside from this cookie for the server to tell the client that it's logged in, and the client to keep track of that state.
If you want the client to know from the ID component itself, you'll want to look at token options like JWTs.

ReactJs How to check user authenticated and sessionID generated by ExpressJs

I have a Nodejs application creating a session when the user gets authenticated.
I see that Expressjs stores the sessionID in a cookie which at the moment is HttpOnly and the session info itself is stored server side.
How to check that the user is authenticated and there is an open session from ReactJS (that is, browser side)?
I think that the only way is to try and access that sessionID? What is a good way of implementing this?
Thanks.
The register or login should respond with the necessary user information to the client side on React so that user information could be stored in the application state (Redux/Flux). The sessionId stored as HttpOnly cookie by express server is solely for the purpose of Express to uniquely distinguish a browser session.
Ideally you would need another API as well to return the user information which at the Express server side should read the sessionId cookie and return with the currentUser information back to the client. Suppose, you login and the user information is stored in the UI application state, and when you refresh the browser, this application state would get flushed off. In such a scenario, this API would help to restore the application state with the current logged in user information. Hope this helps.

angularjs client and spring backend user login and session management

I have a mobile website written in angularjs, with my backend in Spring Boot. Right now, I have my own login page and can login a user without any trouble. However, if the user ever clicks "back", "refresh", etc., the client loses the user's id and login info (obtained from server on login). I need to make sure that this info is maintained and clicking "back" or "refresh" doesn't break everything.
Secondly, a user that knows the url's after login can type those url's in the browser and access them without logging in. I can stop them accessing anything on the server, but not sure what I can do on the client to redirect them to a login page in this case.
Any help would be greatly appreciated!
You should keep in mind that everything running in browser is stateless, there's no way to keep trace of the previous state.
Right now, if the user performs a refresh (or another similar action), Angular loses everything (AuthData included).
You have many way to work around that limit:
Perform an http request after the application bootstrap (have a look at the angular.module().run method
Save a cookie and use the server to print initial data layer directly on the dom via json
Save on local/session storage
Personally, I prefer cookies because that lets the server to work decoupled from the client.
In reference to your comment..."if the user ever clicks "back", "refresh", etc., the client loses the user's id and login info (obtained from server on login)."
Is there any reason you need to maintain the user id or login info after a successful authentication?
If Spring Security is setup for basic authentication, after a successful login, a Session Cookie will be sent back on the response to the client. On all subsequent requests to the server, the same Session Cookie will be sent on the request and the previously authenticated session will be re-established. You just need to ensure that your Angular client is passing cookies when issuing requests.
Take a look at this sample on how this is done.

Persisting authentication token in AngularJS

I'm building an AngularJS application that interacts with an API that uses authentication tokens to authenticate users. Everything seems to be working fine, but I'm struggling with a way to properly persist the authentication token between requests.
At the moment, when a user logs in with correct credentials an authToken is returned, and I'm setting that on $rootScope.authToken. I'm also sending that auth token for future requests, but if I do a hard reload reload the webpage with F5 $rootScope gets cleared and I have to authenticate again.
I'm aware I can store the authToken in a cookie, but would that be the most secure way? Am I better off using local storage to store the token? If local storage is used, would that not get cleared when the user restarts their browser? I'd ideally like the login to persist for a few days.
Firstly, I'm not sure what the format of your authToken is but localStorage should not be used for any sensitive data. Using localStorage works great (and survives browser restarts) as long as your authToken is relatively tamper-proof either through some form of encryption or nonce.
Essentially, you should be careful that since the value is "visible" to all client-side users it should be assumed to be possible to modify or increment.
Have you thought about revocation of login sessions? For example, if you want to log out all active sessions of your application, how would you do it? Since the authToken is stored client-side, you may need to add a timestamp (or some other unique value) to it that can be checked server-side.

Resources