1. 程式人生 > >Azure Key Vault Node.js Step by Step Tutorial

Azure Key Vault Node.js Step by Step Tutorial

Phase 2 (Node.js)

Step 1: (set up node.js and azure module)

Start your new node.js project and install the azure key vault module

npm init

then

npm install azure-keyvault

Step 2 (initialize your code)

Create you base code file normally index.js

echo > index.js

now that this is created we include all the required node modules and authenticate to the key vault.

Authentication

Paste the following code into your index.js file

The code simply loads the Azure key vault module and does the authentication using the app secret to grant us access to read and write the key vault

var KeyVault = require('azure-keyvault');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var clientId = "<application-id-from-azure>";
var clientSecret = "<key-secret-from-azure>";
var vaultUri = "<enter-keyvault-url-from-azure>";
// Authenticator - retrieves the access token
var authenticator = function (challenge, callback) {
// Create a new authentication context.
var context =
new AuthenticationContext(challenge.authorization);
// Use the context to acquire an authentication token.
return context.acquireTokenWithClientCredentials(challenge.resource, clientId, clientSecret, function (err, tokenResponse) {
if (err) throw err;
// Calculate the value to be set in the request's Authorization header and resume the call.
var authorizationValue = tokenResponse.tokenType + ' ' + tokenResponse.accessToken;
return callback(null, authorizationValue);
});
};

Create the Key Vault Client

Next we create a key vault client. This allows us to interact with the authenticated key vault

var credentials = new KeyVault.KeyVaultCredentials(authenticator);
var client = new KeyVault.KeyVaultClient(credentials);

Create new secret

Now that we have our client we can create and store secrets on the key vault.

The following code does just that. The optionsopt parameter is optional but I put it on here to show the options it has

let secretName = 'myserect',
value = 'myValue',
optionsopt = {
contentType: 'sometype',
// tags: 'sometag',
// secretAttributes: 'someAttributes',
// contentType: 'sometype',
// customHeaders: 'customHeaders'
};
client.setSecret(vaultUri, secretName, value, optionsopt).then((results) => {
console.log(results);
})

Retrieve new secret

let secretName = 'mysecret'
secretVersion = '' //leave this blank to get the latest version;
client.getSecret(vaultUri, secretName, secretVersion).then((result) => {
console.log(result);
})

Complete Code

The following documentation link was very useful. You can get some more information on the other functionalities provided by the api.