User authentication using express and react - reactjs

PS
Just note I am pretty new with react(with redux) and express in general.
My question is more of a "what do I do now?" or "help me in the right direction,please" type of question.
My english is very bad.
I am not afraid to teach myself , just show me where to look.
Most internet resources are half explained or assumes you are a pro.
I have a react client side application that needs user authentication, and after the authentication the react application needs to know if client is logged in or out
Now currently my react application is using conditional rendering which means my entire application is depended on the app-level state.
When my react application starts it starts with a login component where the user can add his email and password
Now from here on out I am completely stuck on what to do,so many questions...
How do I authenticate(from the backend) the user using his login input(email/password) and check agiants users in mongoDB if he is there or not, and if he is there how do I let front-end application know he is valid user and use that user information to access certain routes?
How can I check if user is logged in(after authentication and valid user have been authenticated) from front-end react application
Can I use cookies as a possible solution?For example set a cookie on the server-side(express) and access the cookie on the client-side(react) and vice-versa?
Little of topic(or maybe on topic) question? What is Passport.js and it help with my current dilemma ???

as far as authentication is concerned, using a JWT which will be saved in session storage and can be sent to your server app via API is a very popular approach with react/redux applications. this will be sent with all api requests so that the server app can verify that the user is logged in before serving data to them. to check if someone is logged in on the client app, you should have a reducer/saga/thunk that, upon recieving a successful login message from the server app, will update the auth reducer portion of the redux store to flip a boolean isLoggedIn property that you can expose to your props to check if you are logged in.
have a react client side application that needs user authentication, and after the authentication the react application needs to know if client is logged in or out
Now currently my react application is using conditional rendering which means my entire application is depended on the app-level state.
When my react application starts it starts with a login component where the user can add his email and password
there is a react-redux structure called the duck structure that is very good: https://github.com/erikras/ducks-modular-redux
sorry but I do not have mongodb experience but search for authentication handling and there will definitely be examples. .NET Core is excellent and there are many tutorials if you consider changing.

Related

Setting up React app using Firebase and Spotify Web API

I’m in the process of creating a React application that will use Spotify’s web api to compile different types of analytics from each users’ Spotify account.
I set up my react app to use Firebase’s authentication so users can create an account and once logged in, link their spotify to that account.
The goal is to store important info in the user database like the web api’s refresh token so they don’t have to re-link their account in the future when they log in. However, I have very little experience with any of these frameworks and don’t know the best way to handle authenticating each users’ spotify account within my React app.
Should I also create an express server to handle the callbacks for my spotify authentication, database queries, and sending data to the front end, or can all of this be handled in React? And if it can be handled in react, where should I set the callback uri to go? The app has a home page for new users to see its features, and a dashboard page that they go to once logged in.
Sorry if this isn’t very well described, but Im basically just looking for the best practice stack to use for a React-Firebase App that uses the spotify web api, and whether or not I need to separate the spotify authentication into some backend to handle those requests.
I tried setting the callback to go to the Dashboard, but that means every time the user goes to the dashboard it has to check for the callback url parameters that it sends, which doesn’t seem like the best way to handle it.
I also tried creating a /callback page to handle the spotify authentication, which worked but meant there was a random callback page on my site, which also doesn’t seem ideal, so Im not sure what the best way to handle it is.

Login/Authentication with OAuth2 and single-spa

I've started building a prototype for a front-end layer with single-spa. The layout is very similar to https://github.com/react-microfrontends, which means:
Root config
A navbar (React)
Two apps (Both React)
A Styleguide module
An API module to handle communication with a set of API
I managed to get a basic prototype running, but I now need to implement some OAuth2/OpenID based authentication, and I'm not sure where to start. I need the user redirected to a separate URL (Auth0 style) if not authenticated or not having a valid JWT, then I need a mechanism of token refresh whenever the auth token expires. On top of any general advice on best practices, existing examples and so on, I have some specific questions I can't quite work out.
How can I redirect the user to a different URL when not authenticated? Which of the modules/components should be responsible for it?
Is there a library that implements OAuth2 out of the box? In particular, I'm interested in some sort of automatic token refresh.
What is the best way to make sure an unauthenticated/unauthorized user cannot access the app bundles?
Thanks in advance.
The typical approach would be to set up an Auth microfrontend that would :
handle credenials retrieval upon login. Be it via Password flow or OAuth ( in your case). Since you are using React, your OAuth provider should have a library that you can use within the Auth MFE to interact with it. If it's keycloak, React Keycloak is a good fit. There's no rule lf thumb here.
pass the credentials to your two React Apps ( Microfrontends) and the API module via Browser storage or shared state.
Doing so, the API module would set the credentials in the API calls. and the two react Apps would check credentials presence before proceeding with their inner logic.
refresh credentials on expiration or log out user ( depending on your logic ). Loging the user would mean deleting the credentials from browser storage for example.
redirect to one of your react App after login. That means the Auth MFE route should always be active in the root config.
I hope it helps. Here I have summarised the flow.
More of it on my github account https://github.com/exaucae/single-spa-patterns/blob/master/AUTHENTICATION.md

Authentication and Authorization in React app

In a .NET app I can add authentication and authorization using web.config and/or IIS. I can also use [Authorize (Roles = "RoleABC")] in a MVC app's controller or action. And even extend the AuthorizationAttribute
I'm looking into creating a React app for intranet use, and reading these tutorials (ReactJS and MS), but can't find authentication/authorization details.
Even though the app will be Single Page App, I still would like to authenticate and authorize users for certain options within the app, just like I can do in MVC app.
Is the only option to do that way is creating Blazor app instead?
For authentication and authorization, you should use auth tokens (like JWT). Your backend should create an auth token when a client logs in to the system and sends it to the client. Your server also should send the authenticated user information to the client (react app) so that you can render correct pages according to the user type. For example, you can render the admin page for an admin type of user, and the guest page for a guest type of user. You can save this user data as JSON in Redux. Hence you can access the user data from any component of your react. Also, in your backend, you must restrict the endpoints according to the auth token which is sent by the client. In the backend of my app, I follow the below steps:
Authentication check -> Authorization check -> controller (endpoint) -> result
React isn't opinionated on this, so it's up to you to design the implementation. A basic way to do this is:
Log in and obtain an authorized JWT token from the backend and include the account ID when you sign it
Store the JWT token in localStorage, store the account info in Redux
Conditionally limit routes based on account info (ie. admin group) on the front end
Have every auth-required API call include the JWT token in the x-auth-token header, then on the backend use middleware to check if it's still valid. You can then also decode the account ID in order to check its privileges so that you can limit API access
This may be helpful: https://medium.com/#faizanv/authentication-for-your-react-and-express-application-w-json-web-tokens-923515826e0#5f52
Not sure whether you still need this - I personally feel we should have something bridging the authZ gap between server and client to make it easy. So I spent a few days on a github project for this purpose, here it is: authzyin.
What I tried to do is to leverage policy based authorization from asp.net core - which I think it's very cool - and automatically bring the same definition to the client to use in React via hooks.
For authentication I am using msal.js against AAD - so authN is done on the client and jwt bearer token auth is used for all requests.
It has a client lib and a server lib which can be used together or separately. Of course it might still be lacking some features - please feel free to take it as a reference (contribution is also welcome).

ReactJs security

I have just started learning authorization and authentication in react, and I'm writing this after finishing my first simple login system using JWT, as most of you know you store a token in the browser and then you compare it with the saved tokens in your backend now when that validation is done truly I set Authenticated Boolean to true and gain access to the website, after finishing that simple system I checked react dev tools and I found out that I can just change the boolean to true and bypass all of the authentication work!
And I have searched online for resources and tutorials to fix that massive problem but didn't find what was I looking for all I found is how to setup Authentication or protect a router similar to the way I did, but not deeply secured.
So can anyone recommend a course or tutorial paid or free to learn more about security and authentication?
Since React apps are single page apps (if you are doing client-side rendering), the entire application (all html/css/js files) is sent to the client in the initial request. Generally authentication works in the way you have stated where the authentication status of the user is stored in the application state. This, of course, means that someone familiar with web applications would be able to set the variable isAuthenticated to true. If you have sensitive information kept statically (written literally in html/css/js) then this would be an issue.
The reason this scenario is not generally seen as an issue is because React apps usually do not hold any data. And data is usually the sensitive stuff in an app. Data can be tied to the user and should not be exposed to those who are not properly authenticated or do not have the required permissions. Data is held by the server, which can control what it sends out (checking for verified JWTs) via the API to the app. So your server should check for a valid JWT on any request that returns sensitive information—generally all requests except those for the app itself and authentication requests.
In short: Yes, someone can get access to the "authenticated" side of your app, but any requests to the API for data by the app at this point would (or should) be blocked as unauthorized (i.e. status 401). So they can see what the app looks like to an authenticated user, but would not be able to see any sensitive information.
(Note: if you do store sensitive information statically (as mentioned above), consider storing it on the server and having the app request that info via the API and requiring a valid authentication token).
If you would like to block the possibility of an unauthenticated user gaining access to the authenticated side of your app, you could make the login page its own app or HTML doc and only send the full/authenticated version of the app to authenticated users.

React authentication/permissions and component rendering

I am building a project with a React frontend and .NET core backend.
One of the functions of the site is users can submit a form (an event/meetup) which goes to an admin user for approval. Once approved the event is posted on the website along with a list of others from other users.
I then want the user to be able to go to the event/meetup page and when they see their post they should see an edit button (only visible to them and admin) that allows them to modify their post.
This is just one feature of the project but all the others are very similar. User submits data, admin approves, gets posted to live website, user or admin can edit.
I am trying to figure out how to build in authentication/permissions.
I was looking at using JWT tokens.
I am new to React so trying to not use Redux if possible.
What do people suggest as the best way to tackle this?
How do I manage permissions and what parts of a component gets rendered?
Thank you.
Given the scope of the application that you have described, unless you have any unusual authentication requirements, I would simply consider using cookies to track the user.
A user can login via a HTTP request (AJAX or form post) then subsequent requests will include the authentication cookie ensuring that they're logged in.
Like #azium mentioned, this question is not particularly related to React but is standard authentication flow for any web application.

Resources