Authenticate web service urls part 2

ref – https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

In part 1, we set up a simple project where we let a client create a user through a public URL /setup, then display all the users via /api/users.

Next, let’s make sure that we can authenticate a user and then protect those routes using Express route middleware and requiring a token.

Authenticating and Creating a Token

We then use Postman to query it like so

POST_authen_create_user

why – form-urlencoded vs form-data

To summarize, form-urlencoded has a low fixed cost, but high variable for special characters, so application/x-www-form-urlencoded is good for short messages like those found in most basic web forms. On the other hand, form-data has a high fixed costs due to the additional MIME headers prepended to each message chunk, but low variable cost for special characters, so multipart/form-data is good for long messages such images or large files.

Now, copy that whole token string somewhere to be used later.

Protecting URLS

Now let’s protect /api and /api/users by forcing clients to provide the token whenever they need to access these urls.

So for our var apiRoutes that we get from express.Routes(), we have that routing variable use a function to process requests.

We make it run a middleware function by using .use on it. We basically check the requests’ headers to see if the key x-access-token has a valid value. That value should be the token value we received earlier. If the token is valid, everything checks through via the next(), and we run to the apiRoutes.get(‘/users’, function(req, res) {}); function definitions which gets the user from the database and gives it back as a json response.

For example, if you were to hit http://localhost:8080/api/ or http://localhost:8080/api/ it will run this function definition first….see that x-access-token has not been defined in the headers and return you an error json message.

When the tokens are valid, you’ll see the valid json data returned. If you are to use POSTman, here’s what it should look like:

x-access-token_get_user