We can start by testing the /public and /private routes, without any token. The former won't cause any problems, but the latter will be caught by our token testing code and rejected:
> curl "http://localhost:8080/public"
the /public endpoint needs no token!
> curl "http://localhost:8080/private"
No token specified
Now, let's try to get a token. Check out the following code:
> curl http://localhost:8080/gettoken -X POST -d "user=fkereki&password=modernjsbook"
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiJma2VyZWtpIiwiaWF0IjoxNTI2ODM5MDEwLCJleHAiOjE1MjY4NDI2MTB9.cTwpL-x7kszn7C9OUXhHlkTGhb8Aa7oOGwNf_nhALCs
Another way of testing this would be going to https://jwt.io/ and creating a JWT, including userid:"fkereki" in the payload, and using modernJSbook as the secret key. You would have to calculate the expiration date (exp) by yourself, though.
Checking the token at https://jwt.io shows the following payload:
{
"userid": "fkereki",
"iat": 1526839010,
"exp": 1526842610
}
The iat attribute shows that the JWT was issued on 403 error will be produced:
f you wait (at least an hour!), the result will be different; the JWT checking middleware will detect the expired token, and a> curl "http://localhost:8080/private" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiJma2VyZWtpIiwiaWF0IjoxNTI2ODM5MDEwLCJleHAiOjE1MjY4NDI2MTB9.cTwpL-x7kszn7C9OUXhHlkTGhb8Aa7oOGwNf_nhALCs"
the /private endpoint needs JWT, but it was provided: OK!
With this code, we now have a way to add authentication to our RESTful server. If you want, you could go further and add specific authorization rules so that some users would get access to some features, while others would be restricted. Now, let's try to bring everything together, and build ourselves a small REST set of services.