CoffeeScript Question

Consume API with basic authentication using Javascript without exposing key pair

I have a private API, where I'm using basic authentication as my security layer. Right now the API is consumed by my iOS app, so no one is able to see the key pair.

I'm creating the same app for the web now, using React and Javascript and need to consume the same API using basic authentication.

How can I use my API key pair in Javascript without exposing that key pair to the public? Is such a thing even possible?

Answer

As @Andrew mentioned, that is not possible, you can just make it harder to get, but it'll be there somewhere on the client code, and that's enough to say you're exposing it.

If you're open to alternatives, I suggest you to use a per user authentication for the first request, and then a token based authentication for further requests. That token can be a JSON Web Token and it's the flow I'm talking about:

diagram

This is the way it works, taken from JWT's official documentation:

In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used), instead of the traditional approach of creating a session in the server and returning a cookie.

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:

Authorization: Bearer <token>
Comments