Where to store the decryption key in reactjs? - reactjs

I am working on react app which fetches the API on the user responses.
API response are encrypted and I get decryption key before making any API (via secure method).
I need to store the decryption key so that I can decrypt the API response every single time.
Currently I store the decryption key in component state.
which can be seen very easily by anyone using react-dev tool
I don't need to store the decryption locally, it changes very time user login.

I think you can use Cookies for storing your decryption key, but now that's your choice that you need to persist the cookie or make it available for the session.
You can encyrpt cookies making use of cookie-encryption
Hope this helps!!

The key needs to be stored inside an httpOnly cookie, a special kind of cookie that’s only sent in HTTP requests to the server, and it’s never accessible (both for reading or writing) from JavaScript running in the browser.
By the way, this is the way JWT token verification works as well. So you can use the same mechanism.
PS: Ignore my previous comment, I was just trying to give you an alternative without giving my thought to it

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."

Authentication using React and Pyramid (microservices architecture), how to store "session data"?

How are you?
Me..? Well, I'm having some trouble, haha!
I'm using a microservices API architecture on a project where the APIs and GatewayAPI is developed with Python's Pyramid framework, and the main frontend is built with React.
Simple workflow ilustration: https://imgur.com/ifRLLOo
The problem is: where do I safely store the authenticated "session data", like username, user_id, first_name? After logging in, I don't want to make new requests to the user's API just to get these information that will be constantly used.
I know I can store this coded data in the JWT token and store the token in the cookies or the localStorage, but is this the right place? And is this the right process?
If this is the right place, do I need, everytime, to send the decoded data to the frontend as part of the GatewayAPI response?
Thank you for the reading and I hope you guys can save me!
You can store the JWT in a cookie or localStorage it does not matter. I personally do so in localStorage.
Regarding your question about decoding the data, this is handled by the backend. All you need to do is include the JWT in every API call and the API will know which user is calling without the need to send the data back and fort.
I would also recommend you create tokens with an expiration date for added security.
For examples you can take a look at pyramid_jwt

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.

How to authenticate requests to images in an angularJS app using an access_token

I have an angularJS application whose authentication system is made with an access_token and communicating with a backend server written in Go
Therefore to authenticate the user, I have to add the access_token to each request ?access_token=SomeTokenHere or via a header Access-Token: SomeTokenHere
It works great.
The issue is that my backend serves protected images, and I cannot put the access token in the image src for some security reasons(If the user copy/paste the link to someone else, the access_token would be given too ...)
What I'd like to do is to inject a header containing my access token, but since the request is made from the browser it doesn't possible.
This could probably be possible with a cookie, but I'd to avoid using a cookie especially because the angularApp and the backend are not on the same sub-domain.
Another idea would be to create a directive that would get the raw data, and set the data to the image. First I don't know if this is possible and is it a good idea for hundreds of images in the webpage ?
If you have any idea, I'd be glad to hear from you !
Thanks
It is typical problem, and fortunately it was already solved - for example on Amazon S3.
Solution idea is simple: instead of directly using secret key - you can generate signature with access policy, using that key.
There is good algorithm designed especially to generate signatures for this purpose - HMAC
You can have one secret key on your server and use it to sign every image URL before it would be sent to client, also you can add some additional policies like url expiration time...

RESTful Token Authentication Clarification

I've read almost every answer on SO and some blog postings, but I can't figure out one simple thing. In a simple token authentication scheme where the server generates a token and sends it back to the user after verifying credentials, how does the client store and then resend that token in each request? I have seen both cookie examples and header examples. I would like to use the HTTP Headers if possible, but I can't figure out the mechanics of how to send the token to the client, where it will sit, and then have it sent back in the header upon requesting a REST resource.
I am using Jersey/Guice with AngularJS on the front end. Here are the resources I started with:
http://porterhead.blogspot.co.uk/2013/01/writing-rest-services-in-java-part-6.html
Session management : How to generate Authentication token for REST service ? (Jersey)
It depends on your needs. You can use HTTP basic or digest auth, if it is appropriate for you. If not, then if you don't need a permanent storage, you can store credentials in memory. If you need a permanent storage, then you can store them in localstorage, or any other client side storage, but aware, that they are considered not secure.
Anyways I think if your client or service is compromised somehow with xss, then you lost, and it does not matter what else you do about it. Otherwise you can send the credentials in plain text securely as long as you use HTTPS with proper settings. (But that's just an opinion, I am not a security expert, at least not in this topic.) So I think you should concentrate on not being xss vulnerable. For example you should use the proper headers and filter the input against js injection (and by firefox data URI injection). And use TextNode in your client instead of innerHTML wherever it is possible.
For example if you are using Javascript you can store the token in localstorage like window.localStorage["token_id"] on the client side.

Resources