Using Node JS with GameSparks to Store your API Secret
Traditionally, when it comes to web applications, it's common practice to keep secure information on the server side. A secure server that encrypts sensitive data such as passwords and secrets is possibly one of the more effective uses of Node JS. For our case, we want to store the API Secret on the Node Server, and then, using the nonce generated by the client application, return a token with which the client can then initialize GameSparks.
This tutorial explains how to set up and store your API secret on the Node JS server when using the GameSparks platform.
First, make sure you download and install Node on your system so that you are able to run the "node" command from the terminal. If you would like to, you can then download the GameSparks Node utility from our bitbucket repo or by running the npm command "npm install gamesparks-node". However, it will not be necessary for this tutorial.
Writing the Node Script
With this done, we're ready to write our Node script. Let's call it "secretKeeper.js":
- We want to start up a server and have our server handle requests asking for the secret, given a nonce.
- It will then hash the secret with the nonce, and respond with a token for the client to authenticate.
- We're going to be using both the http and crypto packages for our functionality (if you find that you can't require these modules, make sure to install them via npm, for example, "npm install crypto").
First we'll define the PORT we want to use, then embed the API Secret right in the application. Don't worry, it's perfectly secure as long as your server is. We then require the packages we would like to use:
Next, let's create a function that will handle the requests and spit back the response to the client. The request should have the nonce in the url, so we'll look for this, and then using the crypto package, we'll process the hash with Base64 SHA256. This is the auth-token that the client will use to authenticate:
Finally, we'll start up the server and have it listen for incoming requests:
If you are verifying the hmac token being returned by comparing it to a pre-computed nonce through the Test Harness, be sure to use the same Credential to connect with the platform through the Test Harness as the one you used when generating the nonce.
And that about wraps it up!