FrontEnd Headless API
- By captainerd
- 19/12/2024
- 0 comments
FrontEnd API communication
1. Initial API Request and Session Creation
-
Client Initiates: The client sends an initial request to the server with a query parameter,
apitoken=refresh
, to signal that a new session should be created. This request is typically made without any specific session or token information. -
Server Response: The server responds with:
-
Header:
apitoken
containing a custom JWT-like, a base64-encoded with session information (sessionId
,expires
,signKey
). -
Header:
nonce
, which will be used in subsequent requests to confirm the session's validity.
-
2. Decoding the Token
-
Client Decodes Token:
-
The client decodes the
apitoken
header, converting the base64 string into a JSON object. -
The client stores the nonce header.
-
Extracts the fields:
sessionId
,expires
, andsignKey
.
-
3. Nonce Handling
-
Client Stores and Updates
nonce
:-
The
nonce
value is used to protect against replay attacks. -
On each request, the client updates the
nonce
value from the server response header and sends it back to the server on the next request as part of the session.
-
4. Session Signing with Public Key
-
Hashing Steps:
-
Temporary Hash Creation: The client concatenates the
PUBLIC_KEY
(configured both in the client app and server) with thesignKey
received from the server.
const tempHash = PUBLIC_KEY + signKey;
-
Final Hash Creation: The client uses the temporary hash and
sessionId
to create a SHA-256 hash.
const finalHash = crypto.subtle.digest('SHA-256', new TextEncoder().encode(tempHash + sessionId));
-
Store
consumer
Key: The client stores the result of the final hash (theconsumer
key) as long as thesessionId
remains the same. Thisconsumer
key is added to the token before sending it back to the server. -
Rebuilding the Token:
The client adds the
consumer
key to the JSON object containing the session data and converts it back to base64. -
The token is then sent back to the server in subsequent requests to maintain the session.
-
5. Handling Sensitive Operations (e.g., Login)
-
Login Signature:
-
For highly secure operations such as a login, the client generates a SHA-256 hash using the following:
-
const loginSignature = crypto.subtle.digest('SHA-256', new TextEncoder().encode(password + email + PUBLIC_KEY));
-
This s
ignature
is included as a field in the login request to validate the identity securely.
Summary of Client-Side Process:
-
Send initial request with
apitoken=refresh
. -
Decode the
apitoken
header to retrievesessionId
,expires
,nonce
, andsignKey
. -
Store and update
nonce
on each request. -
Sign the session using
PUBLIC_KEY
andsignKey
to generate theconsumer
key. -
Include the
consumer
key in the token for verification in future requests. -
Recalculate the
consumer
key when thesessionId
changes. -
Generate and include a
signature
for secure operations like login.