This sample demonstrates how to secure a Restify API endpoint with Passport using the passport-azure-ad module to handle communication with Azure Active Directory (AAD).
This is the sample code for the article, Secure Node.js Web API with Azure Active Directory.
Before you can connect to Azure Active Directory, you need the following information:
Name | Description | Variable Name in Config File |
---|---|---|
Tenant Name | Tenant name you want to use for authentication | tenantName |
Client ID | Client ID is the OAuth term used for the AAD Application ID. | clientID |
Once you have cloned the repository, open config.js
and add your values for tenant name and client ID in the following code:
const tenantName = //<YOUR_TENANT_NAME>;
const clientID = //<YOUR_CLIENT_ID>;
const serverPort = 3000;
For help on how to determine the values for these variables, read about the Project Setup in the accompanying article.
Once configuration is complete, then install the dependencies and start the project.
npm install
npm start
To test a route that does not require authentication, enter the following command in a bash shell:
curl -isS -X GET http://127.0.0.1:3000/
If you have configured your server correctly, the response should look similar to:
HTTP/1.1 200 OK
Server: Azure Active Directroy with Node.js Demo
Content-Type: application/json
Content-Length: 49
Date: Tue, 10 Oct 2017 18:35:13 GMT
Connection: keep-alive
Try: curl -isS -X GET http://127.0.0.1:3000/api
To test a secured route, enter the following into a bash shell:
curl -isS -X GET http://127.0.0.1:3000/api
If you have configured the server correctly, then the server should respond with a status of Unauthorized
.
HTTP/1.1 401 Unauthorized
Server: Azure Active Directroy with Node.js Demo
WWW-Authenticate: token is not found
Date: Tue, 10 Oct 2017 16:22:03 GMT
Connection: keep-alive
Content-Length: 12
Unauthorized