I created a google project, and setup all I need to use google drive API with JWT crementials.
It doesn't need any auth2 authentification since it's a server-server communication, user are not involved in the process.
This is working fine but why it's not using my account drive?
If I create a folder or a file, I can"t see it in google drive, so is this using a different storage, and if so, do I have a way to see all my files and folder like a normal google drive account?
I'm using nodeJs and so far this worked :
var google = require('googleapis');
var drive = google.drive('v3');
var config = require('../config/config');
var jwtClient = new google.auth.JWT(config.google.drive.client_email, null, config.google.drive.private_key, ['https://www.googleapis.com/auth/drive'], null);
jwtClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
// Make an authorized request to list Drive files.
//drive.files.create({
// auth: jwtClient,
// resource: {
// mimeType: 'application/vnd.google-apps.folder',
// title: 'my new folder'
// }
//},function(err,response){
// if(err){
// console.log('error at gdrive creat folder: ' + err);
// }else{
// console.log('create response: ');
// }
//});
drive.files.list({ auth: jwtClient }, function(err, resp) {
// handle err and response
console.log('err', err);
console.log('resp', resp);
});
});
I'm assuming you're referring to Service Account for the server-to-server interaction.
Its not going in your account since its going to the Service Account's configured user. You can delegate the domain-wide authority to the Service Account but only if you have Google Apps for Work
Related
I want to create azure resources but I am having an issue while generating the token credential for creating such resources.
The following is the way to create azure postgres SQL but I need to Pass the credentials
But I don't know how to generate that token programitaillcay.
I need help for this.
const msRestAzure = require('ms-rest-azure');
const PostgreSQLManagementClient = require('azure-arm-postgresql');
const subscriptionID = '<subscription id>';
const resourceGroup = '<resource group name>';
const serverName = '<server name>'; // must be globally unique
msRestAzure.interactiveLogin().then((credentials) => {
let client = new PostgreSQLManagementClient(credentials, subscriptionID);
return client.servers.createOrUpdate(resourceGroup, serverName, {
location: 'eastus',
properties: {
createMode: 'Default',
administratorLogin: 'postgres',
administratorLoginPassword: 'F00Bar!!'
}
});
}).then((server) => {
console.log('Server:');
console.dir(server, {depth: null, colors: true});
}).catch((err) => {
console.log('An error ocurred');
console.dir(err, {depth: null, colors: true});
});
Does anyone know how to generate it? and using what? It's a signed token I guess using Client Id and tenant ID But how to generate it.
There's no documentation provided to generate it programitially. Is there any way?
interactiveLogin() will provide a link and a code that will allow the user to authenticate from a browser.
When using the Node.js SDK programmatically, there are 2 methods.
1)You could use your username and password to authenticate with the API using your Azure account. It's not recommended because it requires a very high degree of trust in the application, and carries risks which are not present in other flows.
const Azure = require('azure');
const MsRest = require('ms-rest-azure');
MsRest.loginWithUsernamePassword(process.env.AZURE_USERNAME, process.env.AZURE_PASSWORD, (err, credentials) => {
if (err) throw err;
let client = new PostgreSQLManagementClient(credentials, subscriptionID);
// ...
});
2)You may want to use service principal authentication rather than providing your account credentials. It is based on service principal without user account. First, create service principal in Azure portal.
const Azure = require('azure');
const MsRest = require('ms-rest-azure');
MsRest.loginWithServicePrincipalSecret(
'clientId/appId',
'client-secret',
'tenantId',
(err, credentials) => {
if (err) throw err
let client = new PostgreSQLManagementClient(credentials, subscriptionID);
// ...
}
);
For more detail about JavaScript authentication samples using ms-rest-azure library, see here.
Update:
If using service principal, try to add Azure OSSRDBMS Database application permission. Navigate to Azure AD > your app > API permission. And remember to grant admin consent for your tenant.
My Requirement is to copy, list of the files from client(browser) to azure blob using SAS URL. So I am using azure-sdk-for-node, but its look like its not working for me. Can someone recommend any solution or any other library ?.
var azure = require('azure-storage');
var blobSvc = azure.createBlobServiceWithSas('https://XXXXXXXXXX', 'XXXXXXXXX"');
blobSvc.createBlockBlobFromBrowserFile('testmigration', 'taskblob', 'abc.txt', function (error, result, response){
if (!error) {
console.log('file uploaded failed', error);
} else {
console.log('file uploaded success');
}})
ERROR : blobSvc.createBlockBlobFromBrowserFile is not a function
I have successfully uploaded files to Firebase's storage via Google Cloud Storage through JS! What I noticed is that unlike files uploaded directly, the files uploaded through Google Cloud only have a Storage Location URL, which isn't a full URL, which means it cannot be read! I'm wondering if there is a way to generate a full URL on upload for the "Download URL" part of Firebase's actual storage.
Code being used:
var filename = image.substring(image.lastIndexOf("/") + 1).split("?")[0];
var gcs = gcloud.storage();
var bucket = gcs.bucket('bucket-name-here.appspot.com');
request(image).pipe(bucket.file('photos/' + filename).createWriteStream(
{metadata: {contentType: 'image/jpeg'}}))
.on('error', function(err) {})
.on('finish', function() {
console.log(imagealt);
});
When using the GCloud client, you want to use getSignedUrl() to download the file, like so:
bucket.file('photos/' + filename).getSignedUrl({
action: 'read',
expires: '03-17-2025'
}, function(err, url) {
if (err) {
console.error(err);
return;
}
// The file is now available to read from this URL.
request(url, function(err, resp) {
// resp.statusCode = 200
});
});
You can either:
a) Create a download url through the firebase console
b) if you attempt to get the downloadurl programmatically from a firebase client, one will be created on the fly for you.
I'm developing an application with Cordova and would like to save files in Googe Drive.
I've got success in login to Google, using the cordova-plugin-googleplus (https://github.com/EddyVerbruggen/cordova-plugin-googleplus). However I could not get the plugin returns to me accessToken or idToken so I could use with Google javascript API.
window.plugins.googleplus.login(
{
'scopes': 'https://www.googleapis.com/auth/drive.file profile',
'offline': true,
'webApiKey': ‘CODE’
},
function (obj) {
$scope.$apply(function() {
$scope.srcImage = obj.imageUrl;
$scope.NomeGoogle = obj.displayName;
});
},
function (msg) {
alert('Erro');
alert('error: ' + msg);
}
);
I tried using the code below, but returned me the following error:
"Uncaught gapi.auth2.ExternallyVisibleError: Invalid cookiePolicy"
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'REVERSED_CLIENTID',
}).then(function(){
auth2 = gapi.auth2.getAuthInstance();
console.log(auth2.isSignedIn.get()); //now this always returns correctly
});
});
I managed to figure out the problem, why wasn´t getting the serverAuthCode from plugin.
It is necessary to create 2 credentials on the Google Developers Console. The 1st must be Android, this will be for the plugin and the 2nd should be a Web App, this is necessary to achieve serverAuthCode.
The code looks like this
window.plugins.googleplus.login(
{
'scopes': 'https://www.googleapis.com/auth/drive.file profile',
'offline': true,
'webApiKey': ‘REVERSED_CODE of Web App Credential’
},
function (obj) {
$scope.$apply(function() {
$scope.srcImage = obj.imageUrl;
$scope.NomeGoogle = obj.displayName;
});
var data = $.param({
client_id: 'REVERSED_CODE of Web App Credential',
client_secret: 'SECRET_CODE of Web App Credential',
grant_type: 'authorization_code',
code: obj.serverAuthCode
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post("https://www.googleapis.com/oauth2/v3/token", data, config).success(function(data, status) {
//data.access_token;
/** from now you can do use of google API **/
})
.error(function(data, status) {
console.log(data);
console.log(status);
});
},
function (msg) {
alert('Erro');
alert('error: ' + msg);
}
);
Thank you for your reply rojobo
At first I was hoping to skip the need for cordova-plugin-googleplus and just use the gapi within Cordova/PhoneGap to handle authentication with Google, but it appears the gapi client authentication may not work within cordova's file:// protocol.
The answer from #Joao sent me in the right direction, but I kept getting the Invalid cookiePolicy error when trying to use the gapi after retrieving the access_token (this was because I was ignoring step #2 listed below, and after authenticating with the plugini I was mistakenly trying to authenticate again with the gapi).
There is a step (#3 mentioned below) that was unclear to me. To authenticate with Google and then use the gapi in Cordova/PhoneGap, this worked instead...
use the cordova-plugin-googleplus to take care of the authentication and access token retrieval, do not use the gapi at all here
load the gapi client library (skip over the gapi.client.init() call and all the normal gapi authentication procedures)
Attach the access token we got from the plugin to the gapi client, and then make your gapi calls as needed
Step #3 took some digging for me to find, and meant I needed to add the access_token
gapi.client.setToken({access_token:'abc123456xyz'});
Once the access token was attached to the gapi client, I could use the gapi within Cordova/Phonegap:
// Load the YouTube API.
gapi.client.load('youtube', 'v3', function() {
// Do stuff...
};
try
window.plugins.googleplus.login(
{
'scopes': 'https://www.googleapis.com/auth/drive.file profile',
'offline': true,
'cookiepolicy': 'none',
'webApiKey': ‘CODE’
}
I manually created a user in Azure active directory for my project and I am able to get the users. I made a chrome extension and GCM provides me a ID which I want to be linked with the microsoft account.
So for each user, I want a GCM id (got this part) and an Azure AD Id linked together.
I was doing the following:
router.route('/users')
// create a user accessed at POST http://localhost:8080/api/users)
.post(function(req, res) {
// Get an access token for the app.
auth.getAccessToken().then(function (token) {
console.log(token)
var user = new User({
officeId: token,
name : req.body.name,
email :req.body.email,
chromeId : req.body.chromeId
});
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'User created!' });
});
});
});
However, what this does is take the auth token id, chromeId, name and email and just adds it to my mongoose database.
What can I do differently in order to get what I want to achieve? My teammate says what I am doing is correct but I checked the Azure AD and I don't see my user authorized there.
Btw, in the front-end, I ask a user to give their microsoft email and name.
Also, I merged my code with the code found here https://github.com/OfficeDev/O365-Nodejs-Microsoft-Graph-App-only
// #name getAccessToken
// #desc Makes a request for a token using client credentials.
auth.getAccessToken = function () {
var deferred = Q.defer();
// These are the parameters necessary for the OAuth 2.0 Client Credentials Grant Flow.
// For more information, see Service to Service Calls Using Client Credentials (https://msdn.microsoft.com/library/azure/dn645543.aspx).
var requestParams = {
'grant_type': 'client_credentials',
'client_id': config.clientId,
'client_secret': config.clientSecret,
'resource': 'https://graph.microsoft.com'
};
// Make a request to the token issuing endpoint.
request.post({url: config.tokenEndpoint, form: requestParams}, function (err, response, body) {
var parsedBody = JSON.parse(body);
if (err) {
deferred.reject(err);
} else if (parsedBody.error) {
deferred.reject(parsedBody.error_description);
} else {
// If successful, return the access token.
deferred.resolve(parsedBody.access_token);
}
});
return deferred.promise;
};
If you want to create use in your AAD, you can leverage the Microsoft Graph API: Create User, which is not implemented in your code or the graph.js code at github repository.
You need to implement the function yourself like:
Additionally, it seems that we have to generate the access token in Authorization Code Grant Flow to complete the operation. As in my test, I got the Authorization_RequestDenied error when I use the app-only flow access token to authorize the operation, and the graph server returned me the message:
"message": "Insufficient privileges to complete the operation."
you can refer to https://github.com/OfficeDev/O365-Nodejs-Microsoft-Graph-Connect/ for the sample.