I am building and react express app, I am not using server side rendering, where I am facing problem in session management in the client side
So problem. Is like this
I have express route /, /login, /logout, /dashboard
And I also have the same routing in react using react router dom
I used express-session to set the useremail as a session variable in /login route of express app
Then I redirect user to /dashboard . Before redirect user to /dashboard I put authentication code where I check session.useremail is set or not
But when user hit /dashboard to server . Server do authentication . But if user navigate to /dashboard in react client app it just show all the dashboard
You need to check if a user is authenticated or not in your client side. This means if session holds a user or not at that time. Checking authentication depends how you set up your client side logic. But first, you need an Express route to check if session has a user or not. Then you can write your client side code.
If you won't use Redux to handle your state, then you need to go to that Express route every time in a component where you want to check the authentication status. After getting your result you can show the component to a client or redirect them somewhere else depending on that result. I am not a pro, maybe there is another easy way to skip going to that route every time. Maybe we can check for a user in the entry point of the application and write authentication information in a key in localStorage. Then going to Express route, we can check that key in localStorage. I prefer using Redux, handling authentication state there.
If you will use Redux, you can write an action creator and reducer to check the authentication status and set your state (like auth) and check the state where you need.
Related
I'm working on this web app that include several pages.
I really would know if it's better handle the router in the backend (Node.js) or in the frontend (React.js) or with both (I didn't understand in the Internet).
For example, how have I to work with the login page (that will re-direct on the user area).
Thanks
I don't know how big your project is, or its requirements, but if this is a personal project I would suggest using the React Router Library. You can make a call to your Express app from the Front, and based on the response you get back you can route the user to wherever.
In a project of mine I had an express route for login that looked for the user in a database, then checked to see if they provided the correct password. If the user provided the wrong password or if the account wasn't found I sent back an error message. If the user provided the right password I sent a success message to the front. I would listen for the response on the frontend, if I received a success message, I would call useNavigate from React Router to route the user to the user page.
Here is the documentation for React Router Dom: https://www.npmjs.com/package/react-router-dom
If this is a bigger project and you need to think about accessibility and search engine optimization, you would have to find a way to render React from the backend. Its called server side rendering, which I'm not familiar with.
Hope this helps a little.
I am working on a project that use Reactjs for front-end and Expressjs and Passportjs for server side.
The user information will be stored in cookie-session middleware in server side whenever he/she logged in. But every time the user opens the website, the react app will have to fetch user data by sending a http request to the server side and wait for it to response. This sometimes take some seconds or even longer when the connection is poor.
Is there any way to get user's auth state immediately? Thank in advanced!
I have a React single page application using React Router that hooks into a Rails 5 API. The Rails application uses devise_token_auth for authentication. I've successfully created an authentication process that stores the user state in a Redux store on the client side.
Each user of the application belongs to a company. Each company has its own unique subdomain (e.g., companya.foo.com, companyb.foo.com). A user should be redirected to their company subdomain after signing in from foo.com. All requests for an authenticated user should keep them on their own subdomain. Users should be redirected back to foo.com when they sign out.
I read that this is impossible with React Router and the browser API but there has to be a way to achieve this. I also saw some .htaccess suggestions but I am unfamiliar with this approach and I'm not sure if this will handle dynamic redirects.
What is the most intuitive approach to solve this problem?
You would need to redirect to the subdomain and pass the authentication token in the params to keep the user logged in
I have a node server that authenticates with a third party (like stack overflow does) using oauth. When the third party hits my callback and I authorize the request and get the access token and other info, I want to then pass this info to a react app I made, so then the react app can make REST calls to using the access token straight from the provider.
I am new to react and node, but am able to make a node server that can get the access and refresh token info. I am new to 'serving' and serving a react app. I have been serving using
app.use('/client', express.static(__dirname + '/client'));
to serve react apps, and this works great to a limited extent. The situation I am currently in exceeds the extent and I want to learn how to send the oauth info along with my react app back after authorizing in the callback. The flow I am using authorizes the request in the callback and then does a redirect back to the /client route to render the app, which fails to pass any oauth info to the client. Is there any way to set the header before that redirect to have the oauth info, and then some how get that oauth info in the react app?
I am posting here to get some advice on some avenues and resources I should read up on, and maybe some suggestions for my current situation. I am eager to learn more on express and am currently looking to set the header with the info I need and then serving the react app as a file or something, I am not sure yet.
Thanks to all in advanced!
I'll give my best to answer your question. So the problem with SPA(Single Page Application) and OAuth login is that the only way to transfer data with redirects is URL query string. The JWT(JSON Web Token) would allow this, but it's only supported in mobile native SDK-s. Solution for the web, without using the popover flows here:
For Node.js I suggest to use Passport.js OAuth modules, the login flow:
Example /auth/google -> redirect to Google login page.
On success, you get redirected back to callback url /auth/google/callback
You also get back the access_token, refresh_token, basic profile information etc.
No sessions are used so we use the JWT and generate the token on server side.
Redirect back to application with the token: app.example.com?token=JASJKDk..
On client side extract the token from query string.
This is just one possible flow that you might use, instead of JWT you could also use session/cookie solution.
I'm developing a web app on the MEAN stack (MongoDB, Express, AngularJS, and node.js). I'm developing a login system, and will also have some of the Angular routes protected so that only logged-in users can access them. I'm trying to think of the best way to approach the architecture of this.
I'm thinking of the current workflow:
User logs in via AngularJS form, which sends an http POST to an Express endpoint. The endpoint validates the user against the database, and responds with an OAuth token as well as a cookie. Both are stored in the mongo database for later validation.
Once AngularJS receives the login response, it stores the received cookie using ng-cookies, and stores the OAuth token in a User service.
Every time the route changes in AngularJS now, the User service is used to make sure that the cookie is still legitimate by comparing it to cookies in the mongo database (this would be an API call using Angular's resolve... would this create a noticeable lag?)
When a user clicks "log out" or the cookie expires, the cookie and OAuth token are both deleted from the database and will no longer be valid.
Does this approach make sense? Is it secure, and will it be relatively efficient/quick in execution?
I ended up combining my original workflow with Express's auth example, seen here. It is as follows:
When user initially loads the app, an http call is made to an Express endpoint that checks if a session exists already for the user. If so, the user is stored in $rootScope and considered logged in.
Any time the AngularJS route changes, the same endpoint is accessed. Route protection was specified in a way similar to that described here. If the endpoint ever returns that no session exists, $rootScope.user is unset (if it needs to be), and the user is redirected to the login page.
When the login form is processed, it posts to an Express endpoint. The endpoint retrieves the user from the mongoDB (if it exists), and attempts to hash the password. If it's a match, the user's session is set, stored in the mongo DB, and the endpoint returns the user object (used to store in the $rootScope as previously mentioned).
Any time any further endpoints are accessed, the functions are first passed through the restrict function which ensures that a session exists before sending any data to the client. It returns a 401 if no session exists, which is then handled on the Angular side using this HTTP interceptor to unset $rootScope.user and redirect to the login screen.
When the user clicks "log out" on the Angular side, the session is unset and deleted from the mongo DB, $rootScope.user is set to null, and the user is redirected back to the front page.