How it works...

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 5/20/2018, close to 2:00 P.M. and the exp attributes show that the token is set to expire one hour (3,600 seconds) later. If we now repeat the curl request to /private, but adding the appropriate header, it will be accepted. However, if you wait (at least an hour!), the result will be different; the JWT checking middleware will detect the expired token, and a 403 error will be produced:

> 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.126.199