diff --git a/.gitignore b/.gitignore index 00cbbdf53f6c..95f91779d979 100644 --- a/.gitignore +++ b/.gitignore @@ -1,59 +1,60 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directories +projects/* +targets/* +packages/* +test/data/test_package.zip + +# Visual Studio # +*.suo +*.user +.ntvs_analysis.dat +obj/* +examples/obj +examples/.ntvs_analysis.dat +examples/.vs +examples/bin +.vs +TestResults/* +.vscode/* +./**/.vscode/* + +# Node # node_modules/ -jspm_packages/ +npm-debug.log.* +azure_error +checkstyle-result.xml +test-result.xml -# Typescript v1 declaration files -typings/ +# Mac OS # +.DS_Store +.DS_Store? -# Optional npm cache directory -.npm +# Windows # +Thumbs.db -# Optional eslint cache -.eslintcache +# Credentials # +*.cer +*.pfx +*.pem -# Optional REPL history -.node_repl_history +# WebStorm # +.idea/ -# Output of 'npm pack' -*.tgz +# docs # +docs/ +main.conf.json +child.conf.json +.grunt/ -# Yarn Integrity file -.yarn-integrity +# temporary test artifacts +test/tmp/* -# dotenv environment variables file +# dotenv environment variables file .env +# Nuget packages and corresponding codegen sources +.nuget +packages + +# Coverage report +coverage +.nyc_output \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000000..461d6bcf51c3 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +sudo: false +node_js: + - "10" + - "8" + - "6" +before_script: + - npm i -g typescript + - tsc \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000000..c68da2ec6747 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,5 @@ +# Contribute Code or Provide Feedback + +If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](http://azure.github.io/guidelines/). + +If you encounter any bugs with the library please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-node/issues) section of the project. \ No newline at end of file diff --git a/LICENSE b/LICENSE index 21071075c245..183d56b144b7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ - MIT License +The MIT License (MIT) - Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) 2018 Microsoft - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 72f1506a93b5..54a4cc844199 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,147 @@ +# Azure SDK for Javascript -# Contributing +[![Build Status](https://travis-ci.org/Azure/azure-sdk-for-js.png?branch=master)](https://travis-ci.org/Azure/azure-sdk-for-js) -This project welcomes contributions and suggestions. Most contributions require you to agree to a -Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us -the rights to use your contribution. For details, visit https://cla.microsoft.com. +This project provides a Javascript package that makes it easy to consume and manage +Microsoft Azure Services. +It supports SDKs for: +- ARM services (packages with the naming convention of `azure-arm-`) +- data plane of some Azure services (packages with the naming convention of `azure-`). -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide -a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions -provided by the bot. You will only need to do this once across all repos using our CLA. +## Documentation -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. +Documentation of the supported SDKs can be found here: +- https://docs.microsoft.com/en-us/javascript/azure - This website primarily provides SDK documentation for + - ARM based services (`azure-arm-`) + - data plane SDKs like `azure-batch`, `azure-graph`, etc. + +## Authenticating + +There are three ways to authenticate against Azure while using the management plane (`azure-arm-`) SDKs and the `azure-graph` SDK, use +[this guide](./documentation/Authentication.md) to determine which method to use. + +## Install individual modules + +| **Azure Service (Data plane)** | **Install Command** | +| --- | --- | +| [Gallery](http://azure.microsoft.com/en-us/marketplace/) | `npm install azure-gallery` | +| [Graph](https://azure.microsoft.com/en-us/services/active-directory/) | `npm install azure-graph` | +| [Key Vault](http://azure.microsoft.com/en-us/services/key-vault/) | `npm install azure-keyvault` | +| [Monitoring](https://msdn.microsoft.com/library/azure/dn306639.aspx) | `npm install azure-monitoring` | +| [Scheduler](http://azure.microsoft.com/en-us/services/scheduler/) | `npm install azure-scheduler` | +| [Service Fabric](https://azure.microsoft.com/en-us/services/service-fabric/) | `npm install azure-servicefabric` | +| [Service Bus](http://azure.microsoft.com/en-us/services/service-bus/) | `npm install azure-sb` | +| [Storage](http://azure.microsoft.com/en-us/services/storage/) | `npm install azure-storage` | +| [Batch](https://azure.microsoft.com/en-us/services/batch/) | `npm install azure-batch` | +| **Azure Resource Management (ARM) (Control plane)** | +| [Advisor](https://docs.microsoft.com/en-us/rest/api/advisor/) | `npm install azure-arm-advisor` | +| [Api Management](https://docs.microsoft.com/en-us/rest/api/apimanagement/) | `npm install azure-arm-apimanagement` | +| [App Insights](https://docs.microsoft.com/en-us/rest/api/application-insights/) | `npm install azure-arm-appinsights` | +| [Automation](https://docs.microsoft.com/en-us/azure/automation/) | `npm install azure-arm-automation` | +| [Authorization](https://azure.microsoft.com/en-us/documentation/articles/role-based-access-control-configure/) | `npm install azure-arm-authorization` | +| [Batch](https://azure.microsoft.com/en-us/services/batch/) | `npm install azure-arm-batch` | +| [BatchAI](https://docs.microsoft.com/en-us/azure/batch-ai/) | `npm install azure-arm-batchai` | +| [Billing](https://docs.microsoft.com/en-us/azure/billing/billing-usage-rate-card-overview) | `npm install azure-arm-billing` | +| [CDN](https://azure.microsoft.com/en-us/services/cdn/) | `npm install azure-arm-cdn` | +| [CognitiveServices](https://azure.microsoft.com/en-us/services/cognitive-services/) | `npm install azure-arm-cognitiveservices` | +| [ContainerInstance](https://docs.microsoft.com/en-us/rest/api/container-instances/) | `npm install azure-arm-containerinstance` | +| [CosmosDB](https://docs.microsoft.com/en-us/rest/api/documentdbresourceprovider/) | `npm install azure-arm-cosmosdb` | +| [Commerce/Usage](https://azure.microsoft.com/en-us/documentation/articles/billing-usage-rate-card-overview/) | `npm install azure-arm-commerce` | +| [Container Registry](https://azure.microsoft.com/en-us/services/container-registry/) | `npm install azure-arm-containerregistry` | +| [CustomerInsights](https://docs.microsoft.com/en-us/dynamics365/customer-insights/ref/progref) | `npm install azure-arm-customerinsights` | +| [Compute](http://azure.microsoft.com/en-us/services/virtual-machines/) | `npm install azure-arm-compute`| +| [Datafactory](https://azure.microsoft.com/en-us/services/datafactory/) | `npm install azure-arm-datafactory` | +| [Datalake Analytics](https://azure.microsoft.com/en-us/services/data-lake-analytics/) | `npm install azure-arm-datalake-analytics` | +| [Datalake Store](https://azure.microsoft.com/en-us/services/data-lake-store/) | `npm install azure-arm-datalake-store` | +| [DevTest Labs](https://azure.microsoft.com/en-us/services/devtest-lab/) | `npm install azure-arm-devtestlabs` | +| [DNS](http://azure.microsoft.com/en-us/services/dns/) | `npm install azure-arm-dns` | +| [DomainServices](https://docs.microsoft.com/en-us/azure/active-directory-domain-services/) | `npm install azure-arm-domainservices` | +| [EventGrid](https://azure.microsoft.com/en-us/services/eventgrid/) | `npm install azure-arm-eventgrid` | +| [EventHubs](https://azure.microsoft.com/en-us/services/event-hubs/) | `npm install azure-arm-eventhub` | +| [HDInsight](http://azure.microsoft.com/en-us/services/hdinsight/) | `npm install azure-arm-hdinsight` | +| [HDInsightJobs](https://msdn.microsoft.com/en-us/library/azure/mt613023.aspx) | `npm install azure-arm-hdinsight-jobs` | +| [Insights](https://msdn.microsoft.com/en-us/library/azure/dn931943.aspx) | `npm install azure-arm-insights` | +| [IotHub](https://azure.microsoft.com/en-us/documentation/services/iot-hub/) | `npm install azure-arm-iothub` | +| [Key Vault](http://azure.microsoft.com/en-us/services/key-vault/) | `npm install azure-arm-keyvault` | +| [Logic Apps](https://azure.microsoft.com/en-us/services/logic-apps/) | `npm install azure-arm-logic` | +| [Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning/) | `npm install azure-arm-machinelearning` | +| [Machine Learning Compute](https://azure.microsoft.com/en-us/services/machine-learning/) | `npm install azure-arm-machinelearningcompute` | +| [Media Services](https://azure.microsoft.com/en-us/services/media-services/) | `npm install azure-arm-mediaservices` | +| [Mobile Engagement](https://docs.microsoft.com/en-us/azure/mobile-engagement/) | `npm install azure-arm-mobileengagement` | +| [Monitor Management](https://docs.microsoft.com/en-us/rest/api/monitor/) | `npm install azure-arm-monitor` | +| [Notification Hubs](https://azure.microsoft.com/en-us/documentation/services/notification-hubs/) | `npm install azure-arm-notificationhubs` | +| [Operations Management](https://docs.microsoft.com/en-us/azure/operations-management-suite/) | `npm install azure-arm-operations` | +| [Operational Insights](https://azure.microsoft.com/en-us/resources/videos/azure-operational-insights-overview/) | `npm install azure-arm-operationalinsights` | +| [PowerBi Embedded](https://azure.microsoft.com/en-us/services/power-bi-embedded/) | `npm install azure-arm-powerbiembedded` | +| [RecoveryServices](https://azure.microsoft.com/en-us/services/site-recovery/) | `npm install azure-arm-recoveryservices` | +| [RecoveryServices Backup](https://azure.microsoft.com/en-us/services/site-recovery/) | `npm install azure-arm-recoveryservicesbackup` | +| [RecoveryServices SiteRecovery](https://docs.microsoft.com/en-us/rest/api/site-recovery/) | `npm install azure-arm-recoveryservices-siterecovery` | +| [Redis Cache](https://azure.microsoft.com/en-us/services/cache/) | `npm install azure-arm-rediscache` | +| [Relay](https://docs.microsoft.com/en-us/azure/service-bus-relay/relay-what-is-it) | `npm install azure-arm-relay` | +| [Resource Health](https://docs.microsoft.com/en-us/rest/api/resourcehealth/) | `npm install azure-arm-resourcehealth ` | +| [Resource Manager](https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/) | `npm install azure-arm-resource` | +| [Scheduler](https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/) | `npm install azure-arm-scheduler` | +| [Search](https://azure.microsoft.com/en-us/services/search/) | `npm install azure-arm-search` | +| [ServerManagement](https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/) | `npm install azure-arm-servermanagement` | +| [Servicebus](https://msdn.microsoft.com/en-us/library/mt639375.aspx) | `npm install azure-arm-sb` | +| [Service Fabric](https://azure.microsoft.com/en-us/services/service-fabric/) | `npm install azure-arm-servicefabric` | +| [Storage](http://azure.microsoft.com/en-us/services/storage/) | `npm install azure-arm-storage` | +| [Storage Import-Export](https://docs.microsoft.com/en-us/azure/storage/storage-import-export-service) | `npm install azure-arm-storageimportexport` | +| [Storsimple8000series](https://docs.microsoft.com/en-us/azure/storsimple/storsimple-overview) | `npm install azure-arm-storsimple8000series` | +| [Stream Analytics](https://docs.microsoft.com/en-us/rest/api/streamanalytics/) | `npm install azure-arm-streamanalytics` | +| [Sql](https://azure.microsoft.com/en-us/services/sql-database/) | `npm install azure-arm-sql` | +| [Traffic Manager](http://azure.microsoft.com/en-us/services/traffic-manager/) | `npm install azure-arm-trafficmanager` | +| [Virtual Networks](http://azure.microsoft.com/en-us/services/virtual-network/) | `npm install azure-arm-network` | +| [VisualStudio](https://docs.microsoft.com/en-us/rest/api/) | `npm install azure-arm-visualstudio` | +| [WebApps (WebSites)](http://azure.microsoft.com/en-us/services/app-service/web/) | `npm install azure-arm-website` | +| **Base Libraries** | +| Common Functionality for ARM clients generated from Autorest (Generic) | `npm install ms-rest-js` | +| Common Functionality for ARM clients generated from Autorest (Azure) | `npm install ms-rest-azure-js` | + +## Need Help? + +* [Read the docs](https://docs.microsoft.com/en-us/javascript/azure/?view=azure-node-latest) +* [Open an issue in GitHub](http://github.com/azure/azure-sdk-for-node) +* [Microsoft Azure Forums on MSDN and Stack Overflow](http://go.microsoft.com/fwlink/?LinkId=234489) + +## AzureNodeEssentials VSCode extension + +The [AzureNodeEssentials](https://marketplace.visualstudio.com/items?itemName=azuresdkteam.azurenodeessentials) extension helps you easily interact with Azure. +It helps you: +- create a project scaffolding +- install correct dependencies +- ready to use snippets for authentication and deploying templates to azure + +Please feel free to provide feedback for the extension by opening github issues over [here](https://github.com/Azure/azure-node-essentials). + +## Related Projects + +* [Azure CLI](http://github.com/azure/azure-xplat-cli) + +## License + +This project is licensed under MIT and Apache-2.0. +- "MIT" license is usually used for the client libraries generated using [Autorest](https://github.com/Azure/Autorest) that are targeting ARM (V2 version of Azure REST API). The license can be found in "LICENSE.MIT.txt" file in this repository. +- "Apache-2.0" license is usually used for the client libraries generated using an internal code generator that are targeting ASM (V1 version of Azure REST API). The license can be found in "LICENSE.Apache.txt" file in this repository. + +## Contribute + +* If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](http://azure.github.io/guidelines/). + +### Getting Started Developing +Want to get started hacking on the code, super! Follow the following instructions to get up and running. These +instructions expect you have Git and a supported version of Node installed. + +1. Fork it +2. Git Clone your fork (`git clone {your repo} --recursive`) +3. Move into SDK directory (`cd azure-sdk-for-js`) +4. Install all dependencies (`npm install`) +5. Run the tests (`npm test`). You should see all tests passing. + +### Contributing Code to the Project +You found something you'd like to change, great! Please submit a pull request and we'll do our best to work with you to +get your code included into the project. + +1. Commit your changes (`git commit -am 'Add some feature'`) +2. Push to the branch (`git push origin my-new-feature`) +3. Create new Pull Request diff --git a/documentation/EnvironmentVariables.md b/documentation/EnvironmentVariables.md new file mode 100644 index 000000000000..2bd00cb4039d --- /dev/null +++ b/documentation/EnvironmentVariables.md @@ -0,0 +1,12 @@ +## Environment Variables Setup + +```bash +export AZURE_SUBSCRIPTION_ID= +export CLIENT_ID= # Application Id provided by Azure Active Directory (SPN for service principal auth) +export DOMAIN= contosoCorp.com +export AZURE_USERNAME= user@contosoCorp.com # Only set this if you are using user authentication +export AZURE_PASSWORD= # Only set this if you are using user authentication +export APPLICATION_SECRET= # Only set this if you are using service principal auth +export NOCK_OFF=true +export AZURE_NOCK_RECORD= +``` \ No newline at end of file diff --git a/documentation/Node.jsAuth.md b/documentation/Node.jsAuth.md new file mode 100644 index 000000000000..a56a0ff8bad6 --- /dev/null +++ b/documentation/Node.jsAuth.md @@ -0,0 +1,216 @@ +# Authentication + +All service APIs require authentication via a `credentials` object when being +instantiated. There are three ways of authenticating and creating the required +`credentials` via the SDK: basic authentication, interactive login, and service +principal authentication. + +## Basic Authentication + +Simply provide your username and password to authenticate with the API using your +Azure account. It is encouraged that your username and password be stored in +environment variables rather than in the source code for your project. + +```js +const Azure = require('azure'); +const MsRest = require('ms-rest-azure'); + +MsRest.loginWithUsernamePassword(process.env.AZURE_USER, process.env.AZURE_PASS, (err, credentials) => { + if (err) throw err; + + let storageClient = Azure.createStorageManagementClient(credentials, 'subscription-id'); + + // ..use the client instance to manage service resources. +}); +``` + +## Interactive login + +Interactive login will provide a link and a code that will allow the user to +authenticate from a browser. Use this method when multiple accounts are used by +the same script or when user intervention is preferred. + +```js +const Azure = require('azure'); +const MsRest = require('ms-rest-azure'); + +MsRest.interactiveLogin((err, credentials) => { + if (err) throw err; + + let storageClient = Azure.createStorageManagementClient(credentials, 'subscription-id'); + + // ..use the client instance to manage service resources. +}); +``` + +### For azure-graph sdk + +One needs to set the tokenAudience to 'graph' and provide the tenantId in the options object. +```javascript +const AzureGraphClient = require('azure-graph'); +const MsRestAzure = require('ms-rest-azure'); + +const options = { + tokenAudience: 'graph', + domain: '' +}; + +MsRestAzure.interactiveLogin(options, (err, credentials) => { + if (err) throw err; + + let graphClient = AzureGraphClient(credentials, ''); + + // ..use the client instance to manage service resources. +}); +``` + +## Service Principal Authentication + +Interactive login, similar to how the CLI authenticates, is the easiest way to +authenticate; however, when using the Node.js SDK programmatically, you may want +to use service principal authentication rather than providing your account +credentials. This essentially creates keys for your Azure Active Directory +account that you can provide to the SDK to authenticate rather than requiring +user intervention or username/password. + +### Creating a Service Principal + +There are three ways to create a Service Principal, the next sections will walk +you through each method. + +#### 1. Azure Portal + +Follow the steps outlined in the +[Azure Portal documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-group-create-service-principal-portal/) + to generate the necessary keys. + +#### 2. Azure CLI + +This method can be used with either the +[Azure CLI v2.0 (Python)](https://github.com/Azure/azure-cli) or the +[Azure Cross-Platform CLI (npm module)](https://github.com/Azure/azure-xplat-cli). + +_using the Python Azure CLI v2.0 requires just one step_ +```shell +$ az ad sp create-for-rbac +``` + +_Using the Node.js cross-platform CLI requires additional steps for setting up +roles_ +```shell +$ azure login # or $ azure login -u user@domain.tld +$ azure ad sp create -n sp-name -p sp-password +``` + +This will create a new Service Principal and output the keys, copy the output for +use in your script. Note: you can retrieve the keys later by running +`$ azure ad sp list` in your terminal. + +The important fields are marked below (the other required field is the password +that was provided when creating the service principal) + +```shell ++ Creating application sp-name ++ Creating service principal for application **56894bd4-0fde-41d8-a0d7-5bsslccety2** +data: Object Id: weewrerer-e329-4e9b-98c6-7878787 +data: Display Name: sp-name +data: Service Principal Names: +data: **56894bd4-0fde-41d8-a0d7-5bsslccety2** +data: https://sp-name +info: ad sp create command OK +``` + +Next, you'll need to assign a role to the service principal that was just +created. You can get a list of available roles by running `$ azure role list` + +_In this example we are creating the service principal as a Contributor at the +subscription level. A contributor role looks like this in the list_ +``` +data: Name : Contributor +data: Actions : 0=* +data: NotActions : 0=Microsoft.Authorization/*/Delete, 1=Microsoft.Authorization/*/Write +data: IsCustom : false +``` + +This will associate the service principal to your current subscription. Use the +service principal that was returned in the `create` step for the `--spn` option. + +```shell +$ azure role assignment create --spn 56894bd4-0fde-41d8-a0d7-5bsslccety2 -o Contributor +info: Executing command role assignment create ++ Finding role with specified name +data: RoleAssignmentId : /subscriptions/abcdefgh-1234-4cc9-89b5-12345678/providers/Microsoft.Authorization/roleAssignments/987654-ea85-40a5-80c2-abcdferghtt +data: RoleDefinitionName : Contributor +data: RoleDefinitionId : jhfskjf-6180-42a0-ab88-5656eiu677e23e +data: Scope : /subscriptions/abcdefgh-1234-4cc9-89b5-12345678 +data: Display Name : sp-name +data: SignInName : +data: ObjectId : weewrerer-e329-4e9b-98c6-7878787 +data: ObjectType : ServicePrincipal +data: ++ +info: role assignment create command OK +``` + +The service principal can now be used to log in. +```shell +$ azure login -u 56894bd4-0fde-41d8-a0d7-5bsslccety2 -p P@ssw0rd --tenant --service-principal +info: Executing command login +info: Added subscription TestSubscription ++ +info: login command OK +``` + +#### 3. SDK + +Run the [Service Principal creation script](./ServicePrincipal) to +programmatically create a service principal. + + +### Using the Service Principal + +Now you can use the Service Principal keys to authenticate in the SDK. + +```js +const Azure = require('azure'); +const MsRest = require('ms-rest-azure'); + +MsRest.loginWithServicePrincipalSecret( + 'clientId or appId', + 'secret or password', + 'domain or tenantId', + (err, credentials) => { + if (err) throw err + + let storageClient = Azure.createStorageManagementClient(credentials, 'subscription-id'); + + // ..use the client instance to manage service resources. + } +); +``` + +### For azure-graph sdk + +One needs to set the tokenAudience to 'graph' and provide the tenantId in the options object. +```javascript +const AzureGraphClient = require('azure-graph'); +const MsRestAzure = require('ms-rest-azure'); + +const options = { + tokenAudience: 'graph', + domain: '' +}; + +MsRestAzure.loginWithServicePrincipalSecret( + 'clientId or appId', + 'secret or password', + 'domain or tenantId', + options, + (err, credentials) => { + if (err) throw err; + + let graphClient = AzureGraphClient(credentials, ''); + + // ..use the client instance to manage service resources. +}); +``` diff --git a/documentation/ServicePrincipal/package.json b/documentation/ServicePrincipal/package.json new file mode 100644 index 000000000000..f86b15472ae6 --- /dev/null +++ b/documentation/ServicePrincipal/package.json @@ -0,0 +1,34 @@ +{ + "name": "azure-sp", + "author": "Microsoft Corporation", + "contributors": [ + "Zavery, Amar " + ], + "private": true, + "version": "0.1.0", + "description": "Sample script for creating a service principal in Azure.", + "tags": [ + "azure", + "sdk" + ], + "keywords": [ + "node", + "azure" + ], + "main": "./spCreate.js", + "license": "MIT", + "dependencies": { + "ms-rest": "^1.15.0", + "ms-rest-azure": "^1.15.0", + "azure-graph": "1.1.1", + "azure-arm-authorization": "3.1.1" + }, + "homepage": "http://github.com/Azure/azure-sdk-for-node", + "repository": { + "type": "git", + "url": "git@github.com:Azure/azure-sdk-for-node.git" + }, + "bugs": { + "url": "http://github.com/Azure/azure-sdk-for-node/issues" + } +} \ No newline at end of file diff --git a/documentation/ServicePrincipal/spCreate.js b/documentation/ServicePrincipal/spCreate.js new file mode 100644 index 000000000000..ec538049c00f --- /dev/null +++ b/documentation/ServicePrincipal/spCreate.js @@ -0,0 +1,184 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + */ + +'use strict'; + +// Different basic role types that can be assigned to a ServicePrincipal. + + /////////////// + //Contributor// +/////////////// +// Name : Contributor +// Id : b24988ac-6180-42a0-ab88-20f7382dd24c <<<<<< +// Description : Lets you manage everything except access to resources. +// AssignableScopes : 0=/ +// Actions : 0=* +// NotActions : 0=Microsoft.Authorization/*/Delete, 1=Microsoft.Authorization/*/Write +// IsCustom : false + + ///////// + //Owner// +///////// +// Name : Owner +// Id : 8e3af657-a8ff-443c-a75c-2fe8c4bcb635 <<<<< +// Description : Lets you manage everything, including access to resources. +// AssignableScopes : 0=/ +// Actions : 0=* +// NotActions : +// IsCustom : false + + /////////// + // Reader// +/////////// +// Name : Reader +// Id : acdd72a7-3385-48ef-bd42-f606fba81ae7 <<<<< +// Description : Lets you view everything, but not make any changes. +// AssignableScopes : 0=/ +// Actions : 0=*/read +// NotActions : +// IsCustom : false + + + ////////// + //Steps:// +////////// +// 1. Validating environment variables. +// 2. Creating an AD application +// 3. Creating a ServicePrincipal on top of the AD application +// 4. Assigning the "Contributor" role to the SP created in step 3 at the subscription scope. +// 5. Trying to login as the created SP. We have induced a timeout of 20 seconds. Still this may fail. +// However, that is fine. Executing the ServicePrincipal login in a separate script should work after a minute or so. + +validate(function () { + var msrestazure = require('ms-rest-azure'); + var graph = require('azure-graph'); + var authorization = require('azure-arm-authorization'); + var util = require('util'); + var moment = require('moment'); + + var tenantId = process.env['AZURE_TENANT_ID']; + var subscriptionId = process.env['AZURE_SUBSCRIPTION_ID']; + var passwordForSp = process.env['AZURE_SP_SECRET']; + var displayName = process.env['AZURE_SP_DISPLAY_NAME']; + var homepage = 'http://' + displayName + ':8080'; + var identifierUris = [ homepage ]; + var roleId = 'b24988ac-6180-42a0-ab88-20f7382dd24c'; //that of a contributor + var scope = '/subscriptions/' + subscriptionId; // we shall be assigning the sp, a 'contributor' role at the subscription level + var roleDefinitionId = scope + '/providers/Microsoft.Authorization/roleDefinitions/' + roleId; + var loginOptions = { + domain: tenantId + }; + msrestazure.interactiveLogin(loginOptions, function(err, creds) { + if (err) { + console.log('Error occured in interactive login: \n' + util.inspect(err, { depth: null })); + return; + } + var options = { + domain: tenantId, + tokenAudience: 'graph', + username: creds.username, + tokenCache: creds.tokenCache, + environment: creds.environment + }; + var credsForGraph = new msrestazure.DeviceTokenCredentials(options); + var graphClient = new graph(credsForGraph, tenantId); + var startDate = new Date(Date.now()); + var endDate = new Date(startDate.toISOString()); + var m = moment(endDate); + m.add(1, 'years'); + endDate = new Date(m.toISOString()); + var applicationCreateParameters = { + availableToOtherTenants: false, + displayName: displayName, + homepage: homepage, + identifierUris: identifierUris, + passwordCredentials: [{ + startDate: startDate, + endDate: endDate, + keyId: msrestazure.generateUuid(), + value: passwordForSp + }] + }; + graphClient.applications.create(applicationCreateParameters, function (err, application, req, res) { + if (err) { + console.log('Error occured while creating the application: \n' + util.inspect(err, { depth: null })); + return; + } + + var servicePrincipalCreateParameters = { + appId: application.appId, + accountEnabled: true + }; + console.log('Underlying Application objectId: ' + application.objectId); + graphClient.servicePrincipals.create(servicePrincipalCreateParameters, function (err, sp, req, res) { + if (err) { + console.log('Error occured while creating the servicePrincipal: \n' + util.inspect(err, { depth: null })); + return; + } + var authzClient = new authorization(creds, subscriptionId, null); + var assignmentGuid = msrestazure.generateUuid(); + var roleCreateParams = { + properties: { + principalId: sp.objectId, + //have taken this from the comments made above + roleDefinitionId: roleDefinitionId, + scope: scope + } + }; + + console.log('>>>>>>>>>>>\nSuccessfully created the servicePrincipal: \n' + util.inspect(sp, { depth: null }) + '\n'); + authzClient.roleAssignments.create(scope, assignmentGuid, roleCreateParams, function (err, roleAssignment, req, res) { + if (err) { + console.log('\nError occured while creating the roleAssignment: \n' + util.inspect(err, { depth: null })); + return; + } + + console.log('>>>>>>>>>>>\nSuccessfully created the role assignment for the servicePrincipal.\n'); + console.log('>>>>>>>>>>>\nIn future for login you will need the following info:'); + console.log('ServicePrincipal Id (SPN): ' + sp.appId); + console.log('ServicePincipal Password: ' + passwordForSp); + console.log('Tenant Id for ServicePrincipal: ' + tenantId); + console.log('>>>>>>>>>>>\n'); + console.log(util.format('\nTrying to login as the created servicePrincipal.\n\nWaiting for \'20 seconds\' for the changes to reflect. ' + + 'If this call fails then please try to login as the servicePrincipal by executing the following script:\n\n' + + 'var msrestazure = require(\'ms-rest-azure\');\n\n' + + 'msrestazure.loginWithServicePrincipalSecret(\'%s\', \'%s\', \'%s\', function(err, creds) { if (err) { console.log(err); ' + + '} else { console.log(creds); } });', + sp.appId, passwordForSp, tenantId)); + setTimeout(function(appId, secret, tenantId, callback) { + msrestazure.loginWithServicePrincipalSecret(sp.appId, passwordForSp, tenantId, callback); + }, 20000, + sp.appId, passwordForSp, tenantId, function (err, spCreds, subs) { + if (err) { + console.log('\nError occured during servicePrincipal login: \n' + util.inspect(err, { depth: null })); + return; + } + + console.log('\nServicePrincipal login is successful.\n'); + return; + }); + }); + }); + }); + }); +}); + +function validate(callback) { + var ids = []; + var envs = ['AZURE_TENANT_ID', 'AZURE_SUBSCRIPTION_ID', 'AZURE_SP_SECRET', 'AZURE_SP_DISPLAY_NAME']; + envs.forEach(function (item) { + if (!process.env[item]) { + ids.push(item); + } + }); + + if (ids.length > 0) { + console.log('Please set the following environment variables:\n\t' + ids.join(', ')); + process.exit(); + } + callback(); +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 000000000000..e160267ceb8e --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "azure-sdk-for-js", + "author": "Microsoft Corporation", + "version": "0.1.0-preview", + "description": "Microsoft Azure Client Libraries for JavaScript with TypeScript type definitions", + "private": true, + "tags": [ + "node", + "azure", + "sdk", + "typescript", + "browser" + ], + "keywords": [ + "node", + "azure", + "sdk", + "typescript", + "browser" + ], + "license": "MIT", + "homepage": "http://github.com/azure/azure-sdk-for-js", + "repository": { + "type": "git", + "url": "https://github.com/azure/azure-sdk-for-js.git" + }, + "bugs": { + "url": "http://github.com/Azure/azure-sdk-for-js/issues" + }, + "scripts": { + } +} diff --git a/swagger_to_sdk_config.json b/swagger_to_sdk_config.json new file mode 100644 index 000000000000..b9c35eed4ab2 --- /dev/null +++ b/swagger_to_sdk_config.json @@ -0,0 +1,12 @@ +{ + "meta": { + "autorest_options": { + "typescript": "", + "license-header": "MICROSOFT_MIT_NO_VERSION", + "sdkrel:node-sdks-folder": ".", + "use": "@microsoft.azure/autorest.typescript@^2.0.0" + }, + "repotag": "azure-sdk-for-js", + "version": "0.3.0" + } +} \ No newline at end of file