Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure the JavaScript API Access Token?

There are numerous online resources which provide JavaScript APIs to access their services. To be more clear, I will base my question on the example of MapBox, but this applies well to many other services in various domains.

When someone wants to use such a service in a web application (like the map imagery from MapBox for example), they typically need to Register/Sign Up and obtain an access token to access the service.

Now, if I would use the API from the server side - there is no issue: I know my token is stored securely somewhere on the server and is only exposed upon communication between my server and the service provider, which is OK as long it is HTTPS. However, in case of a JavaScript API (for example if I use Leaflet to render a map from MapBox), I am supposed to have my access token in a JavaScript which is exposed to the user's web browser - and so it makes it extremely easy to find someone's access token. My users, or in a case of a public service, literally anyone, would be able to find the token in the browser's "Dev Tools".

This token however, as for me, should be considered as a sensetive data - service usage is tracked based on the authentication this token provides. If you pay for the service based on its usage it becomes critical, but even if you don't (like, if you use a Free/Starter/Non Paid plan) - service usage is limited and I'd like to be sure it is only me who uses it.

Is my only option a proxy via my own web server?

Is there a way to secure the access token used by a JavaScript API to access an external service, provided that JavaScript is executed in a user's browser?

like image 586
Timur Avatar asked Jul 24 '15 12:07

Timur


People also ask

Where should I store my token in JavaScript?

To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.


Video Answer


1 Answers

Restrict Access with CORS

Make your web server return the access tokens on an ajax request from you javascript with CORS setup. Token can be captured with this method visiting your app.

Provide Tokens to Authorized Users

You can also add authentication on your webserver to provide limited access to the users you allow. Token can be captured with this method but only by authorized users.

Proxy Requests

The only way to completely protect that token is to proxy the requests through your server. Token cannot be captured with this method. Note that this may be against terms of service.

like image 111
jpoehnelt Avatar answered Sep 20 '22 19:09

jpoehnelt