Next.js and Nest.js authentification - reactjs

I have a project where I use Next.js on the front-end and Nest.js on the back-end.
I want to use a JWT authentification method via email and password.
My question is:
What is the best way to implement an authentification for Next.js with custom Back-end.
I'm sending API requests through redux-saga to get some data from back-end.
For me the Set-Cookies from the back-end not work. It's not applying on the client browser.
For now my possible solution is to create a custom axios instance and somehow do the Auth check there.
But I'm sure there should be a better solution, thanks for help!

For now my possible solution is to create a custom axios instance and somehow do the Auth check there.
Yes. This is the correct way of going about it. Give the token to whatever you use for queries and let it handle it for you.
You have a number of different ways of achieving this.
Provide it via a side-effect
Whenever a login event happens, run a side-effect to configure your axios instance to always send the newly acquired token with each request
Set the token in your cookies or localstorage and let axios retrieve it for each request
Set the token in a context and only make requests through that context with a hook

Related

What is the best way to store an admin API token in Next.js ? Feel like storing it client side as http only cookie is risky

I'm working on a e-commerce using next.js and sylius API and the API admin routes are secured using JWT. So in order to fetch products (for example), i need to login to the API, get the token and then fetch the products using the token. The most common method to be able to send the token on every new requests to the API is to store it in a HTTP-only cookie.
As the pages are generated statically, i feel i don't need (and want) to expose the API token to the client. So i'm wondering the best way to store the token ?
Here the different options i have in mind right now:
store the token as a http only cookie and use it server side (with a proxy using next js API pages) in order to call the sylius API. Like i said, i'm not confortable to store the API token into the client, it seems risky to me, as it will be exposed to everyone, and with that token you can access the admin API.
configure the API in order to prevent the token from expiring, and store it in the next js app as an environnement variable (.env.local), so that it's not exposed to the client and can be used for fetching the api when generating static pages. The official ecommerce theme of Next.Js seems to use that method (https://github.com/vercel/commerce/blob/f770ad7a91059a2ecfbb9de1bac111dfe7016124/framework/bigcommerce/api/index.ts#L82)
store the token somewhere in the next js structure but not as an environnement variable (maybe a config file?), so that it can be replaced if necessary (if the token expires etc).
get the token and store it in the react state as is it will be used once only for generating all static pages. On each build the token will be asked again by the API and then used for fetching the API for exporting the static pages with the content. It don't need to be saved more time than the building step.
For me the last option seems better but i feel i'm missing something there, i'm kinda new to next, so i'm not sure exactly if its a good solution.
Thanks :)
I get a great answer from a reddit user ("supermaguireray"), so i post it as an answer here:
"First of all, in any session management mechanism the correct information needs to live on the correct domains, what I mean is that your client can only have access to a identification information, but never to data used in the server, these can be applied to a server-side session, when a ID for the user data stored on the server is sent to the client (preferably encrypted), or in a JWT where a encrypted string is sent to the client (identification), and decrypted on the server (Data).
With that said, the only reason you should send the API token to the client is if you need to fetch data directly from a browser. Storing as a httpOnly cookie is the most secure way.
In case you only need the cookie fetch data to the next backend, to render your SSG or ISR pages, there is no need to send a cookie to the client. Just store the token in your server. I would store it as env variable. Use next.config.js->runtime-configuration.
Or, you can keep a expiration date for the token, and store the credentials, maybe even in a DynamoDB or FaunaDB app."

How to make authentication with React JS

I'm working on a simple frontend in react.js and a backend in node.js. At the moment I'm working on a Login that should work as follow:
The Frontend send username and password to the backend
Obtain a token that will be needed for all the following requests to the backend
Now all my files in the frontend should see the obtained token so they can use it to send the requests when needed, how can I do this, considering that not all the components in my React.js frontend are childs of the Login? Should I make a global variable? If yes how? Thank you in advance
After getting your token from node server, you can use useContext() hook of React and provide the token as value to the components. This is the simplest way in my opinion. Otherwise, if you are familiar with redux, flux etc, you can use them as well.
I think you can use localStorage to store the token you received from the backend and simply get it from localStorage when you need it.

How to store generated api keys in React?

If a user logs in with user and password, he gets an new api key,
so react can access the Rest Api with his user account. How do you save this api key? And what happend if the user clicks 'refresh page'?
Of course I can initalize the Rest App every time with
<script>
window.REP_LOG_API_KEY = '19e8317a38b24af82da056f6ed36e831ea6b8f9bfcad996aaa56ec773f9f2e1d';
</script>
<script src="build/reactapp.js"></script>
but dont look very secure (but I like the idea of changing this key
every page request, if you have no single page application and react
is only used here and there).
To store the Api Key in a cookie would be also possible (secure but not
httponly, normally I only use safe cookies). Is this the only way?
I'm still not quite sure how to use react with a rest api
with individual api keys. Thany you.
The API key you are talking about is probably cookies/authentication token. If it is cookies, you need to enable httpOnly to prevent attacks. For authentication token, the most common way to store is in localStorage or sessionStorage. However, it is insecure, even with HTTPS and short expiry dates (and you do HAVE to use them). Putting it in Redux store is the same as putting it in a global js object where everyone can see.
What will protect your app is to check standard headers to verify the request is same origin (source and target origins check) and CSRF token. Also a common pattern is to verify the token signature before storing and using it. You can check out Auth0 blog on where to store it here: https://auth0.com/docs/security/store-tokens
There are several ways to do this. If you are using a state management library like Redux, MobX, Flux etc, then you can put it there.
Another place to store them is in the browser local storage. This will keep the token saved even if the user refreshes the page or open a new tab etc. Yet I am not 100% sure whether it's a safe thing to do.
Or you can attach it to the Rest Client itself. IMO, this is the best way to do it. I will summarize the steps to do that in brief.
Create a Rest Client by wrapping a solution like fetch-api or axios.
Add a module state, where you can store any data
Whenever making a call, check if there is a token, if a token is not there in the state, then authenticate first.
If the token is there, use it to make the api call. If the request fails with a 403(or may be 401. It depends) error, that means the token has possibly expired. So authenticate again and update the token.
Something like this,
class ApiClient {
constructor() {
this.token = null;
}
login(username, password) {
// make the call to login
// set this.token with the response
}
request() {
// Make the API call using the token
}
}
What will happen with a refresh? Then since the token is not there, the authentication will need to happen again. This will not be a problem if you use cookies to manage sessions.
You can put it in Redux store. I think it is the best implementation.

Securely storing auth token in React Frontend

I am currently working on a single page react app. This app will not require any login and it will be publicly available.
I am making a POST request to a webhook of another API that I do not have access to and that I do not maintain. This API required me to send an authentication token via the POST. I wonder how I can securely store this token so that it does not get out in the world. I need to send it as is so storing it in a cookie that a backend provides is not an option. Storing in in JWT will not work as I can decode that without the secret.
Is there even a way to store the token without exposing it to the world?
I hope the issue is clear, if not let me know and I'll explain better.
Thank you all for your time!
I would usually have a local Express server running and proxy the request through that.
You would set up a route in your Express app that you would POST to from your React front-end, this Express route handler then makes the call to the external API from the server side which has the token to put in the header. Then the response is returned to your React front-end without it knowing anything about the external API or tokens.
You can't store the token in front-end. either you need to use
cookies/session to store the token. If you want to store the token you
need to encrypt it and store it will be the better option.
Please check here to understand the JWT token mechanism
if the web app doesn't have a login. you can't generate token without user details.
The token should be passed in the header of the request for best practices.
If you're using create-react-app to instantiate your React project, have you looked into using an environment variable to store the token? It's not 100% safe and secure, check here for the cons, but can be a quick fix without a separate proxy request. You can make an .env file (make sure to add it to your .gitignore if using git) in the root of your directory and define variables there. They need to start with REACT_APP, like REACT_APP_SECRET=1234 and can then be referenced where you need them in your app with process.env.REACT_APP_SECRET.
Read more about environments in React here.

How to send POST login request to a rails api-only app using React?

I have a working rails RESTful api-only app.
I use Postman to consume that api. Now, to use the api the user have to login to http://localhost:3002/authenticate first by setting content-type to application-json in Header then Email and Password's value in body. After sending the POST request to the server I get auth-token as a json response. Then after successful login I have to pass that auth-token as a Authorization key in each GET request to get respective data.
Now, I want to build a UI for that back-end api as I learn React js. But till now all tutorials I could find was how to send GET requests without any authorization factor. And they are using axios, redux etc.
Can any-one please guide me on where should I start or how to
approach this problem?
Do I necessarily have to use a third-party library for this purpose?
If so which will be better axios or redux??
Any beginner friendly tutorial link would be of tremendous help
How start
Securing React Redux Apps With JWT Tokens - Rajaraodv explains how you get a jwt token and how to keep it in the front end app. I think this way will fits for you.
Keep the auth-token
Rajaraodv uses localStorage to keep the jwt token, you can use the same or keep directly in redux store, it's your choice, the best manner that fits you.
Ajax call
You can use Axios to make Ajax calls, or use fetchApi from the browser as Rajaraodv did, it's up to you.
Explains
"If so which will be better axios or redux??" these two libraries are totally different, each with it's own purpose.

Resources