How to start a virtual machine on Azure with node.js? - javascript

I am using the Azure node.js SDK. https://azure.microsoft.com/en-us/develop/nodejs/
Strangely I cannot find documentation for starting a virtual machine on Azure using the node.js SDK.
I need a clear example of how to launch an Azure virtual machine using the node.js SDK.
Also I need reference documentation that specifies all the optional parameters for launching a Virtual Machine using the node.js SDK.

Here's one example.
var startVirtualMachine = async function(resourceGroup, vmName){
try {
let credential = await msRestAzure.loginWithServicePrincipalSecret(process.env.AZURE_CLIENT_ID, process.env.AZURE_APPLICATION_SECRET, process.env.AZURE_TENANT);
computeClient = new ComputeManagementClient(credential, process.env.AZURE_SUBSCRIPTION_ID);
await computeClient.virtualMachines.start(resourceGroup, vmName);
return true;
} catch (error) {
throw error;
}
}

You can use the REST API to manage your VM. To start a VM, it's here. There is no options though.
You can then use request for example to issue your POST request.

As I known, you can use the Virtual Machine REST API of Azure Resource Management to start your VM with the parameters subscription-Id, resource-group-name & vm-name, please move to the doc https://msdn.microsoft.com/en-us/library/azure/mt163628.aspx to know the start API for Azure VM.
Note: the api-version required is 2015-06-15
The API with POST request need to be authenticated via set up request header Authorization: Bearer <access token>.
For requesting access token, you can refer to the offical sample code https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/blob/master/sample/client-credentials-sample.js to get the token from the code tokenResponse.accessToken.
Or you can use the function VirtualMachineOperations.start of the node package azure-arm-compute to start VM with the same parameters above, please refer to the doc http://azure.github.io/azure-sdk-for-node/azure-arm-compute/latest/.

Related

How to get a read only permission token on dbx for the client side?

Generating a Dropbox token will give write access to the project folder, which is why i need a read only token to use on the client side
I haven't been able to do anything because I haven't found any option on the developer dashboard to see the individual tokens and their permissions
var fetch = require('isomorphic-fetch');
var Dropbox = require('dropbox').Dropbox;
const dbx= new Dropbox({
accessToken: 'yourAccessTokenHere',
fetch:fetch,
});
Dropbox has released "scopes" functionality on the Dropbox API, which you can use to configure an app or access token to only a limited set of functionality, such as the ability to read but not write files.
You can find more information about the release in our blog post here:
https://dropbox.tech/developers/now-available--scoped-apps-and-enhanced-permissions

How to Call a Firebase Authenticated Cloud Endpoint from Javascript?

I've written several Google Cloud Endpoints in Python and have followed the directions to require that calls to them come from users authenticated using Firebase. I need to call my Endpoints from a web app using JavaScript, but I can't seem to get the authentication working.
I'd like to use the Google APIs client (gapi) which comes with the added benefit of dynamically generating the client library from a provided discovery document. When I try using the gapi client, I can make the call to my API just fine, but I get an HTTP 401 as a response, along with the HTTP unauthorized message that my python source returns.
Google's documentation on the subject is rather sparse. I gather from one tutorial on the subject that a standard Ajax call can be used, but I don't see any documentation on how to call a Firebase authenticated endpoint from Gapi. My current concern is that the gapi client may not be set up (yet) to allow for the use of a discovery doc and also allow for the Authorization header to be set as Firebase Auth requires.
Is what I'm attempting even possible?
Any suggestions would be appreciated. Perhaps calling a Firebase Authenticated endpoint isn't possible using the gapi client.
Here's a rough outline of my gapi js code:
function(token) {
gapi.client.init({
apiKey: 'MY_API_KEY',
discoveryDocs: [MY_DISCOVERY_DOC_URL'],
clientId: 'MY_WEB_CLIENT_ID',
scope: 'profile'
}).then(function(){
return gapi.client.my.server.api.call();
}).then(function(response){
console.log(response.result.data)
}, function(reason){
console.log('Error: ' + reason.result.error.message)
});
}
I have been struggling with this for a while now and finally made it work. I found two options:
Option 1) If you want to use the gapi.client library:
There is a method called gapi.client.setToken(tokenObject) - documentation
However, it seems to be new (July '17) and little documentation or examples are available. I made it work doing the following (this is in angularJS with angular-fire but I hope you get what I am doing, basically ignore the "$scope")
// any time auth state changes, add the user data to scope
$scope.auth.$onAuthStateChanged(function (firebaseUser) {
$scope.firebaseUser = firebaseUser;
$scope.idToken = null;
// get the token from the firebase User Object
// Note that getToken() is deprecated and for me it did not work as desired
// use getIdToken() instead
firebaseUser.getIdToken().then(function (idToken) {
$scope.idToken = idToken;
});
});
// Now you can use setToken
// If from the docs you were thinking firebase's getIdToken() gives me TokenObject and gapi's setToken()
// expects a TokenObject so I'll just pass it - you'd be wrong! (at least for me - if it works for you please give me a heads up)
// You'll need to build your own token:
var homemadeToken = {
access_token: $scope.idToken.toString() // This feels so wrong
};
gapi.client.setToken(homemadeToken);
gapi.client.yourapi.getSomething().execute(function (resp) {
// Do stuff with the response
}
);
Option 2) Use jQuery's Ajax request - documentation
$.ajax(backendHostUrl + '/_ah/api/yourapi/v1/someendpoint', {
headers: {
'Authorization': 'Bearer ' + $scope.idToken // Here it worked without making a string first but I did not check why
},
method: 'GET',
success: function (resp) {
// Do stuff with the response
}
});
If after all of that your backend is still not accepting the tokens and you have migrated from endpoints v1 to v2, it might help migrating again as described here. Esp. make sure the lib folder is created again.
Even after SDK updates, I noticed that if and once you migrated from v1 to v2 the "lib" folder is never updated regardless of whether or not it hase been updated.
Still not working?
This github page fixes the issue on the BACKEND side for an earlier version - the backend did not accept firebase tokens and needed to be hacked. If you want to apply the changes as described there and you are using the latest "lib" folder's (writing in July '17) users_id_token.py as per migration guide, note that the file has changed and you need to go against the explicit commentary in that file's _verify_signed_jwt_with_certs method:
# Formerly we would parse the token body here.
# However, it's not safe to do that without first checking the signature.
and parse the token before checking the signature. From that file's comments it can be inferred however, that Google plans to put the entire logic elsewhere - hopefully firebase friendly and safely.

Authenticating using OfficeDev/office-js-helpers rather than adal

I'm working on an Office Add-in that currently uses adal to obtain an auth token.
As I want to use the Fabric front end I am changing it to React and I notice that the officer-js-helpers have implemented authenticators that seem to do the same job as the adal library.
Am I correct in this assumption? If so, how do I duplicate this adal config using the office-js-helpers authentication functions:
var adalConfig = {
instance: 'https://login.microsoftonline.com/',
tenant: 'myprivatesite.onmicrosoft.com',
clientId: 'xxx-xxx-xxx-xxx-xxx',
endpoints: {
'https://my.private.url.endpoint/path': 'https://myprivatesite.onmicrosoft.com/path.to.something',
}
And this token request:
var authContext = new AuthenticationContext(adalConfig);
authContext.acquireToken('https://myprivatesite.onmicrosoft.com/path.to.something', function (error, token) {
console.log(token)
});
UPDATE:
I have got the adal.js library working in my react app. I have used some of the code from the init function in the adalAuthenticationService angular provider to retrieve the authentication token.
So the question remains. Can I use the office-js-helpers to do the same thing?
Adal.js cannot be used out of the box for web add-ins authentication because within the sandboxed iFrame context of a web add-ins you cannot navigate simply to the authentication login page hosted outside your domain.
Office-js-helpers uses the dialogAPI when available and a popup as a fallback solution when not available.
If I remember correctly Office-js-helpers targets only Azure AD v2.0 (which comes with a lot of nice new features comparing to Azure AD). I guess it is a good choice.
I created an Open source sample the documentation can be interesting to you. However, this is not exactly what you want it is based on an AuthorizationCode flow while you are looking for Implicit flow.
OK It appears it is extremely easy. All that is required from the adal configuration is the client Id and the tenant.
if (OfficeHelpers.Authenticator.isAuthDialog()) {
return;
}
var authenticator = new OfficeHelpers.Authenticator();
authenticator.endpoints.registerAzureADAuth('xxx-xxx-xxx-xxx-xxx', //clientId
'myprivatesite.onmicrosoft.com' // tenant
);
authenticator.authenticate(OfficeHelpers.DefaultEndpoints.AzureAD)
.then(function (token) {
console.log(token);
.catch(function(error) {
console.log(error);
});

Okta integration with JavaScript

I have been tasked with integrating an existing JavaScript application with Okta.
This application requires access to certain resources on Amazon's AWS API Gateway. The API-Gateway-generated SDK requires an access key and a secret access key for which we would prefer to use temporary credentials.
According to AWS documentation, an assertion is required to make a call to AWS's AssumeRoleWithSAML in order to retrieve temporary credentials.
I've tried the following Okta resources, but have been unable to determine how to obtain an assertion using JavaScript:
AWS SAML Integration with Okta:
This setup allows for logging in to the AWS Console.
The Okta Sign-in Widget: Using the widget, I've been unable to find an assertion in what is being returned.
Okta API/SDK: A JavaScript API/SDK is not listed.
I have found a few Python implementations that return temporary access keys, but haven't found any examples or documentation describing a JavaScript approach with Okta.
Thank you.
Here is an example application showing how to integrate Okta with Amazon S3 in JavaScript, using the Okta Sign-In Widget: https://github.com/okta/okta-oidc-aws
This example application is based on Amazon's JavaScript in the Browser sample application, but authenticates against Okta using OpenID Connect instead of using Facebook, as Amazon's sample application does.
Please note that the current version of the Okta Sign-In Widget (1.7.0) includes the xhr library which conflicts with Amazon's JavaScript SDK. This will be fixed in version 1.9.0 of the Okta Sign-In Widget, which removes xhr. In the meantime, the example in the okta-oidc-aws repo ships with a custom version of the widget that has xhr disabled.
The GitHub repository for the okta-oidc-aws sample has full details on getting the example working.
At a high level, the important parts are as follows:
Get an OpenID Connect id_token from Okta.
Use the WebIdentityCredentials class to exchange the Okta id_token for an AWS IAM Role. This is known as "Web Identity Federation".
The code that does this is below, and is copied straight from the sample.html file in the example:
AWS.config.credentials = new AWS.WebIdentityCredentials({
RoleArn: AWS_ROLE_ARN,
WebIdentityToken: res.idToken
});
AWS.config.credentials.get(function(err) {
if (err) {
console.log("Error creating AWS Web Identity: " + err);
return;
}
bucket = new AWS.S3({
params: {
Bucket: AWS_S3_BUCKET_NAME
}
});
oktaLoginContainer.style.display = 'none';
uploadDialog.style.display = 'block';
listObjs();
});

Always using the same OAUTH code with Dropbox-js

I'm using the official Dropbox JS library in a Node.js server. It only ever needs to authenticate as a single user, and it can't go through the whole OAUTH browser setup every time the server starts. I am attempting to write an auth driver that pretends to be like the NodeServer driver, but runs the callback straight away with a code that always stays the same.
Here's what I've got (it's coffeescript, but you get the idea):
myAuthDriver = {
authType: -> return "code"
url: -> return "http://localhost:8912/oauth_callback" # What the url would be if I were using NodeServer
doAuthorize: (authUrl_s, stateParam, client, callback) ->
authUrl = url.parse(authUrl_s, true)
callback({
code: "[a code I just got using the NodeServer driver]"
state: authUrl.query.state
})
}
Running authenticate with this driver set causes this error:
Dropbox OAuth error invalid_grant :: given "code" is not valid
The docs say that this should only occur with a broken auth driver (but it doesn't give any ideas for fixing it).
Does anyone with more knowledge of OAUTH or Dropbox know what's wrong here?
Note: I've found in several places online that Dropbox OAUTH codes never expire
Once you have an OAuth 2 access token, you can just do var client = new Dropbox.Client({token: '<your token>'});. No need for an auth driver at all.
(If you want an easy way to get an access token, consider using https://dbxoauth2.site44.com.)

Categories

Resources