Introduction to the problem
I have on the one hand a REST API in PHP and on the other hand a web application that consumes said API. The problem I have is that I only want to authorize the use of the REST API for my web application (and in the future, for example a mobile app).
The thing is that most of the REST API is protected from that because only requests with a header Authorization: Bearer "User token"
can get and request resources from that user (and as far as I know, by not using cookies to identify the session from the API side , there is no risk of CSRF attacks or any other if the necessary measures are taken to deal with the storage of said token).
However, what do I do with the login, registration, etc. paths? These are without sessions and that means that anyone could create users or log in from another place (It's not because of "spam" since there are limits by IP and captcha) but I don't like anything that happens for several reasons.
Ask
The solution seems to be to create a token for each API client that authorizes it to use it, but if the app is developed entirely in JavaScript, with no server-side languages, how do I use and store this token without exposing it?
If it's with CSRF tokens in the login form, how do I implement it from a web in JavaScript so that no one else can just do the same thing?
I'm sorry to tell you that you can't Reference :
Personally the closest thing would be to obfuscate the related token/javascript, but this is not considered good LINK practice .
As well as not being able to hide, well no, there are many ways to capture the API Key as with any token. But you can prevent abuse by generating tokens that have a limited lifetime and that it is not easy to generate them on the client side, for example CSRF tokens or nonces can work.
A very easy option to use is the anonymous firebase "authentication" token, you can generate one at the moment the user accesses the registration or login route and limit its duration. Where you handle your request you require that the token be valid and if it is not or comes without a token, you reject the request.
Like CSRF tokens or nonces, since the key that generated the token is not exposed to the browser, it can only be verified in a service with access to the validation key. The advantage with Firebase is that you have to maintain almost no infrastructure and you can focus on logic and write very little validation code.
Basic examples with the supported libraries are exposed in the firebase documentation, but there are community libraries for many languages, for example I implemented it for Ruby and PHP: https://firebase.google.com/docs/auth/admin /verify-id-tokens#verify_id_tokens_using_the_firebase_admin_sdk
If you update your question with how you've tried and it works for you, you could even show your solution right here or we can help you round up the solution.