Challenge: Securing APIs
Practice defining an API in Auth0 and collect access control parameters by updating our Credit-Check service.
Exercise
For this exercise, you’ll define an M2M identity in Auth0 for your credit-check
service and then update your code to support access control using OAuth and JWTs. Along the way, you’ll use the security bash scripts to request a valid JWT and then use it to make secured requests of your updated credit-check
service.
Defining the API in Auth0 and collecting access control parameters
- First, sign into the Auth0 website and define or create a new API called
bigco-credit-check
. Then collect the five important access control parameters (name, client ID, client secret, domain, and identifier) and update your copy of theauth0.txt
file in yoursecurity
folder. - Next, use the
auth0-token.sh
script to request a valid JWT access token for use in HTTP calls to your API. Copy the token value in the response into thecurl-auth.txt
file. - Finally, use the http://jwt.io website to validate the access token you were issued by the
auth0-token.sh
script.
Updating the credit-check-secure
Node.js project
- First, update the project’s package collection by adding the proper OAuth packages using npm.
- Next, open the
index.js
file in thecredit-check-secure
project folder in the terminal below and update that file to reference theapi-auth.js
code file from the/darrt/lib
folder. Add the security middleware into the Node/Express pipeline by adding the following lines to yourindex.js
file:
//*********************************************** // start of auth support
var secure = require('./darrt/lib/api-auth.js'); app.use(secure.jwtCheck);
// end of auth support
//***********************************************
- Next, open the
/darrt/lib/api-auth.js
file and update theauth
object values to match the access control parameters you pulled from the Auth0 website in the previous step.
Testing your API security
Now you can try accessing your API to validate your security changes.
- First, try using a simple cURL
http://localhost:8181/
call (without a security token) to confirm that your API call gets an HTTP401
status code response.
Note: Don’t forget to run
npm run dev
in theusercode/onboarding-api/credit-check-secure
folder in the second terminal by clicking the “+
” sign.
- Now use the
curl-auth.sh
utility (with the access token from the previous step and other appropriate configuration settings) to make the same call. This time you should get the root response as expected, without any errors.
You now have a fully secured API service using OAuth and JWT.
Get hands-on with 1400+ tech skills courses.