How do you maintain secrets on the client-side?
In one sentence - there are no secrets client-side. If you don’t want anyone to know about the secret, you should not send it to the client.
The need for secrets
Client may need user ids/passwords, API keys, API secrets etc. None of them can be trusted to the client. Your cookies can be read by a user or a client-program, your local storage is readable by users or third party sites, and your code is accessible by users.
So, how does one manage a secret?
Have a server
Client will depend on the server to manage secrets. Clients pass through an authentication layer so that they can get access to services, resources and more.
Authentication to trust clients
Authenticate client using sessions, JWT etc. Do not store user id/passwords on client.
If you absolutely need to remember sessions, store JWT token in a cookie. But remember - cookies can be read.
Authentication to server is like a key that unlocks other keys. All those unlocked keys are still managed on server.
All third-party services through server
Do not trust clients to manage third party transactions for your app - e.g. fetch data, perform financial transactions, and other such good stuff.
You will not entrust client with your API to third party servers - may it be a subscription service to News website, your GitHub account, or a key to “make payment” to a payment processor.
Even if a client does a transaction directly with third party, your server has to confirm the transaction from the concerned third party - independently. The flow will be -
- Client tells server that it needs to do a payment
- You open third party pop-up to enable transaction
- Client/user does transaction
- Either third party pushes that transaction to you, or you query the site to confirm a successful transaction
Only when these are complete, will you show a confirmation message to client.
What happens if you don’t have a server?
You may have a “middle-ware” kind of application that you and the client can trust in case there is no server. For e.g. you have a service that sends a ‘contact me’ email since the client is requesting the same through a form in your site that has a specific domain.
Or, you will entrust the responsibility of enabling trust to a third party like auth0, which does stuff for you without needing a server of your own.