Loic P. Loic P. - 3 months ago 14
Javascript Question

How to set up session token between JS and PHP API?

I have designed a simple HTML/CSS and JS/jQuery application, and now it's the moment of authentication integration. On the server side, I have done a REST API which allows clients to get some data. But, now I want to authenticate each request with access and/or session token.

I read many websites to find agreements or advice to establish security between the client (JS) and the REST API (PHP), but unfortunately I found nothing or not interesting.
So I ask you to enlighten me (if you want) to know what to do, what to implement, conventions, etc.

What I read:

Designing a Secure REST (Web) API without OAuth

Token Based Authentication for Single Page Apps (SPAs)

I cannot post more links according to my reputation...

Just give me advice, ways how to store private token (RSA) or access/session token for API.

Don't hesitate to give your reaction, and tell me if I'm not exact or something else.

Answer

Authenticating REST API's with JavaScript front-ends is difficult because the JavaScript code is completely readable by anyone visiting the site so storing any kind of login credentials is no good.

With a standard Server to Server set-up simply using basic auth over HTTPS is more than enough but basic auth is no good for SAP JavaScript applications as the credentials are in plain view.

For SAP's you need to be looking at JSON WebTokens, as your back end is in PHP you need to be looking at PHP-JWT from firebase. You can get the code here: https://github.com/firebase/php-jwt or recommended using composer:

composer require firebase/php-jwt

The package makes implementing JWT super simple see the docs for a complete code example. Also check out the JWT for a complete break down https://jwt.io/