AngularJS: is this a bad practice for authentification? - angularjs

I'm new in AngularJS. I use Drupal as Backend for APIs.
So this is my problem:
When the user is logged-in, Drupal saves automatically the SessionNAME = SessionID in the cookie to keep the user logged-in so on refresh the user is still logged-in but i loose the userId, the username, his email, his favorite movies...
My solution was: sending a request to the server in app.run() to get logged user data and I store these data in AuthetificationService.currentUser so if a user is logged i will have all his data otherwise currentUser will be NULL.
Is that a bad practise?
NOTE: Please if your suggestion will be webStorage or cookieStorage tell me exactly what i need to store and when i need to empty the cookie or the local-storage.

Here's the practice I follow and is usually used:
Login->
create session on server ->
store the user object and important info in localstorage
e.g.
localStorage.setObject("myApp_user",user);
localStorage.setObject("myApp_movies",movies);
Refresh Page (check session)
check session(if logged in) ->
get the user data from localStorage and use it
e.g
UserService.user = localStorage.getObject("myApp_user");
MoviesService.movies = localStorage.getObject("myApp_movies");
Logout
close session call on server->remove cookies->remove data from localStorage.. e.g.
localStorage.removeItem("myApp_user");
localStorage.removeItem("myApp_movies");
Hope this helps.

Related

storing username and email in a session

I am using nodejs backend where I send a httponly cookie (xss protected via nodejs backend) with a jwt token.
And this question is on front end. I need to get logged in user. my front end is react.
Tutorial I followed used res.local = currentUser in a isLoggedIn middleware. so for every request currentUser is sent if logged in.
I was thinking , 1. I found out I can't access res.local from react.
2. So then instead of that I can send my response object with isloggedin:true and logindata:currentUser. Now if I do this. For every request this middleware runs and attach currentUser object. Is this a safe thing to do?.
3. Or can I save username and email on a session when user log in, and let middleware to only send isloggedIn true or false in response. then I can read session and use user details if isloggedin is true.
I need to know out of these two what is the best practise.and safe to use. If I let user comes in every request(but this includes just any page even when I retrieve product details, current user will tag along in the request) it is easy. else I will have to read sessions as well. (xss protected via nodejs backend)

Persisting User Sessions with Httponly Cookies in React

I'm trying to figure out what the best way is to fetch user data / persist user sessions on the client side via React, when using HttpOnly cookies to store session data.
I was thinking of doing something like:
useEffect( () => {
const getSession = async () => {
const session = await fetch('/session/current')
if(session){
.... there is an active session
.... set the local state to hold user data
}
}
getsession();
}
So the issue I'm trying to figure out is, when the user logs in and closes the browser, then re-enters my website. How do I validate that the user still has a valid session, and then send necessary user data to the client side to know that the user is authenticated?
When the user logs in and cloes the browser, there is still a valid session HttpOnly cookie on the server side. Is the best way to just hit an endpoint, see if there is a valid session, then return user data?
There is no way to handle this from client side as it is an httponly cookie. You need to send the cookie to the backend to validate session. If users close and reopen their browser, they loose their cookies. In order to keep them logged in you will need to track some other information from the user like their IP address, OS, browser type, etc and save it in like memory cache for a ttl. But it is not secure to do it that way.
First of all, once your get the cookie or token from the server after user logs in, you will have to store in it local session storage in browser itself, so if user closes the browser and reopens it would have automatically logged out,
Or do mention ttl, so that it will have some expiry time as well

saving userType in ReactJs thorughout the session

I am using ReactJs and Nodejs with mysql as my backend, I am maintaining user session via express-session and setting cookie header in my browser. The problem is that I want to display components based on role (eg.admin or user). I am sending the userType from database to React app,in response to the successful login.
How can I maintain and store this userType througout the session so that I can manage my roles.
I dont think local Storage is a good option.
P.S: I have also key:value pair of userType inside the cookie which I am receiving in my browser.but I dont know how to extract userType from the cookie
If you are having a single cookie, ie userType, you can simple do this in componentDidMount or any other applicable control location:
let userType = document.cookie.split("=")[1]
console.log(userType) //your cokkie value
Else, if there are many cookies, you can follow this:
var cookies= {};
document.cookie.split(/\s*;\s*/).forEach(function(pair) {
pair = pair.split(/\s*=\s*/);
cookies[pair[0]] = pair.splice(1).join('=');
});
console.log(cookies.userType)
Storing in a cookie/local storage is fine you just have to make sure the user is authenticated server-side for a certain privilege.

best way to keep user logged in using JWT and axios

how to keep the user always logged in, in a react application.
I can't refresh the token using an expired token, can I ?
my idea is to make the token expiration to null and refresh it in every request for security
so if user don't use the app for a while, token will never expires, and in every request the token will be refreshed for the security
it's not secure to do this. because now the token will still valid as long as no new requests from the user. tokens that never expire extend the time-frame for attacks such as cross-site request forgery (CSRF), session hijacking and session fixation. also if you want to change this behavior you will need to change it from backend side not react.js side
I might be misreading your question, but at least just on "how to keep user logged in"
You can do this with localStorage, ofcourse there is security concern.
Basic idea: user logins, the user object returns from database, you only need to store the jwt_encoded information that makes a user "looks like is logged in" in the localStorage. By that I mean, you aren't going to return the user's password & email everytime, and on refresh page, log the user in with those credentials... If you are building a todolist app, just store the todolist tasks & username to the localStorage after the user logs in for the first time. And then if the user refreshes the page, just display the information from the localStorage.
It might be a little bit more tricky because UI is dynamic and you have to change your localStorage to change your UI, but on backend calls that update our user object, we can simply return the new user object and set that as the new user in localStorage.
Best to check this article for code, https://blog.bitsrc.io/build-a-login-auth-app-with-the-mern-stack-part-3-react-components-88190f8db718. The author starts talking it about half way through. I only provided theoretical stuff.
Edit: I really was falling asleep. For the "it might be a little bit tricky part" I was being quite dumb. If you saved the user id in the localstorage, you can just make api calls to retrieve the user information with that id whenever you need it, in short, you only need to store user id in localStorage.

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.

Resources