I am working on Excel Web Add-In. I am using OfficeDev/office-js-helpers library for authenticating user. Following code is working fine. But I don't know how to get user's email, user name etc.
Is there any function available in OfficeDev/office-js-helpers through which I can get user info ?
if (OfficeHelpers.Authenticator.isAuthDialog()) {
return;
}
var authenticator = new OfficeHelpers.Authenticator();
// register Microsoft (Azure AD 2.0 Converged auth) endpoint using
authenticator.endpoints.registerMicrosoftAuth('clientID');
// for the default Microsoft endpoint
authenticator
.authenticate(OfficeHelpers.DefaultEndpoints.Microsoft)
.then(function (token) {
/* My code after authentication and here I need user's info */ })
.catch(OfficeHelpers.Utilities.log);
Code sample will be much helpful.
This code only provides you the token for the user. In order to obtain information about the user, you'll need to make calls into Microsoft Graph API. You can find a full set of documentation on that site.
If you're only authenticating in order to get profile information, I'd recommend looking at Enable single sign-on for Office Add-ins (preview). This is a much cleaner method of obtaining an access token for a user. It is still in preview at the moment so it's feasibility will depend on where you're planning to deploy your add-in.
Once you have the Microsoft token, you can send a request to https://graph.microsoft.com/v1.0/me/ to get user information. This request must have an authorization header containing the token you got previously.
Here is an example using axios :
const config = { 'Authorization': `Bearer ${token.access_token}` };
axios.get(`https://graph.microsoft.com/v1.0/me/`, {
headers: config
}).then((data)=> {
console.log(data); // data contains user information
};
Related
I am trying to get a simple JSON package from putting the URL of my Google spreadsheet so I can use it on my webpage; I am using my Google Cloud Console API as it is said on the documentation of the v4 Google API format, but I still get the error of "Unauthorized API"
Documentation: https://developers.google.com/sheets/api/guides/migration#v4-api
I am using this URL:
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/Sheet1?key=API_KEY
My google sheet is set as published on the web. And also I am the creator of the google sheet.
What could I be missing? I am new to API's!
First Edit:
Answering the comment of ABDULLOKH MUKHAMMADJONOV
Here is the code I am using to make a GET request to the google sheet, you can see the Sheet ID is there, and also the API of the google cloud platform.
fetch("https://sheets.googleapis.com/v4/spreadsheets/1S652uS2FLVoZ1m3apb6R4H783v6GkV58HbQ6Idec5aY/values/Sheet1?key=AIzaSyCpFZ7mcqMNc6Q_bP6h1kCEfAi6c_fd8AM", {"method": "get"})
.then( (httpResponse) => {
if (httpResponse.ok) {
console.log(httpResponse.json());
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} )
.then(json => console.log(json.someKey))
.catch(err => console.log(err));
This code is from the Wix code editor.
The caller doesnt not have permissions
Means that the user you are authenticated as does not have permission to do what it is you are trying to do.
The method
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/Sheet1?key=API_KEY
I believe is this method spreadsheets.values/get if you check the documentation you will notice that it requires authorization with one of these scopes
You appear to only be sending an api key. You need to be authorized to access that sheet. You cant access it with an API key that only grants access to public data.
Ok, so I investigated about the OAuth 2.0 authentication and authorization for using Google Sheet's REST API. I added one of the needed scopes.
But I am stuck at the point on how to do the authorization process...
I am looking at this google documentation - How to use Google OAuth 2.0 authorization
But I haven't been able to get to the answer I seek. I am stuck at the part where it says "When your application needs access to user data, it asks Google for a particular scope of access." I do now know how to code this request or to do this request through the Insomnia software.
I am trying to do the GET request with a wix testing website, and also with Insomnia, but I haven't been able to achieve it.
These are the images from Insomnia, which tell me "Invalid authorization URL"
Insomnia's OAuth 2.0 authentication parameters
Insomnia's API Query parameter
I want to authenticate to Odoo from an express application using token. I am using odoo-xmlrpc node module to connect Odoo with
my express app. Odoo requires users of the API to be authenticated before they can use any other API. And this node module provides this function
const odoo = new Odoo({
url: config.odooUrl,//odoo url
db: config.odooDB,//odoo db path
username: "john#gmail.com",
password: "john_pass123"
});
odoo.connect(function(err, uid) {
if (err) {
errors.auth = "invalid cridentials";
return res.status(400).send(errors);
}
//execute something from/to odoo server
})
The problem is, I have to enter the user's credentials every time I want to execute an Odoo command. And if I store the user's password it would be stored as a plain text.
My question is, is their token-based authentication to Odoo that can be used through API. Or any other alternative solution to my problem
Currently in Odoo unfortunatelly there is no good solution to this. There is work in progress for support for api token access and 2-factor authentication in this pull request: https://github.com/odoo/odoo/pull/33928.
There are also multiple Odoo rest api modules in app store that support token authentication. You can find these with seach ”rest api” or ”token”. To me none of these have been perfect for my use-cases. I look forward to get native support for this in Odoo Community.
I am building a SPA using vue.js which has a PHP backend server (slim framework 3). These are two separate projects, leave on two different servers and the backend has no front end at all.
SPA (vue.js) makes requests to backend via ajax.
Now I want to implement Google Calendar API to create a calendar and events every time user creates a todo item. To do that I need server to server access to Google Calendar API (I might need to make changes to the event on GCAL even if user is not logged in).
What I am trying to understand, how can I get the access token (and refresh token) using Google JS library using vue.js and save this in the db so that my backend can use it to make offline requests to GCAL Api.
When I use the Oauth v.2 using the JS library, all I get is the access_token which cannot be using for server to server communications.
[UPDATE]
Ok, a little bit more information. I am following the guides from Google and my front end looks like this at the moment
jsbin
So I can successfully authorise user and access their calendar using the javascript sdk. But the token Javascript SDK returns is something like this
{
_aa: "1"
access_token: "xxxxxxx"
client_id: "yyyyyyyyyy"
cookie_policy: undefined
expires_at: "1456400189"
expires_in: "3600"
g_user_cookie_policy: undefined
issued_at: "1456396589"
response_type: "token"
scope: "https://www.googleapis.com/auth/calendar"
state: ""
status: Object
google_logged_in: false
method: "AUTO"
signed_in: true
token_type: "Bearer"
}
I send this token to my backend server and try to make a request to GCAL api as follows
$token = $request->getParam('token');
$client = new Google_Client();
$client->setApplicationName('Web');
$client->setScopes([Google_Service_Calendar::CALENDAR]);
$client->setAuthConfigFile(ROOT_DIR . '/client_secret.json');
$client->setAccessType('offline');
$client->setAccessToken(json_encode($token));
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
And it returns error saying the token is expired. I checked the Google Code and found out the reason it returns this error is because of these lines
public function isAccessTokenExpired()
{
if (!$this->token || !isset($this->token['created'])) {
return true;
}
// If the token is set to expire in the next 30 seconds.
$expired = ($this->token['created']
+ ($this->token['expires_in'] - 30)) < time();
return $expired;
}
As you can see the token that comes from the front end doesn't have created field as well as no refresh_token field.
Thanks for updating the question! I am thinking the issue is that using the client-side flow does not allow you to get a refresh token. From the docs:
OAuth 2.0 client-side flow (AKA Implicit flow) is used to obtain
access tokens (it does not support the issuance of refresh tokens) and
is optimized for public clients known to operate a particular
redirection URI. These clients are typically implemented in a browser
using a scripting language such as JavaScript.
The authorization server MUST NOT issue a refresh token.
see for more: How to get refresh token while using Google API JS Client
You'd need to use the server-auth flow to get a token you can refresh and use long-term. Here's a quickstart guide for PHP.
One other thing to consider is that you will only receive a refresh_token the first time someone authorizes your app. After that, auth attempts will only return an access token. So if you lose the refresh token, you will need to either disable the authorization from your google account, or use the "force re-auth" option in the API.
I'm trying to get graph api data for public Facebook events rendered in an html document. The site I need to put it on is made with a website builder so I don't have control over the server that generates the html. I can only insert JavaScript code into the page.
The only solution I've found now is by using an app access_token in the client side request:
FB.api(
"/<event_id>?fields=start_time,description",
function (response) {
if (response && !response.error) {
console.log(response.start_time, response.description);
}
},
{access_token: "<app access token>"}
);
I've read through the docs on access tokens
and the JavaScript sdk docs, but the app token solution I've found is not secure (from the docs):
... app access token should never be hard-coded into client-side code.
I don't think the user access token is the flow I want because I don't want people to have to log in; it's only for public events. I don't think the page access token is right either.
Is there:
a way to use the Graph API for public events without requiring a user to log in or without introducing an insecurity?
or a way to make sharing my app access token with the world have no bad consequences?
Can I access Google Analytics data using a service account in a client-side application? If not, are there other ways of achieving the same outcome?
Must be entirely client-side, and must not require users to authenticate (hence the desire to use a service account).
Yes you can in https://code.google.com/apis/console make sure you say that its a Service account it will give you a key file to download. With that you dont need a user to click ok to give you access.
For a service acccount to work you need to have a key file. Anyone that has access to that key file will then be able to access your Analytics data. Javascript is client sided which means you will need to send the key file. See the Problem? You are handing everyone access to your account. Even if you could get a service account to work using javascript for security reasons its probably not a very good idea.
You can use the official (and alpha) Google API for Node.js to generate the token. It's helpful if you have a service account.
On the server:
npm install -S googleapis
ES6:
import google from 'googleapis'
import googleServiceAccountKey from '/path/to/private/google-service-account-private-key.json' // see docs on how to generate a service account
const googleJWTClient = new google.auth.JWT(
googleServiceAccountKey.client_email,
null,
googleServiceAccountKey.private_key,
['https://www.googleapis.com/auth/analytics.readonly'], // You may need to specify scopes other than analytics
null,
)
googleJWTClient.authorize((error, access_token) => {
if (error) {
return console.error("Couldn't get access token", e)
}
// ... access_token ready to use to fetch data and return to client
// even serve access_token back to client for use in `gapi.analytics.auth.authorize`
})
If you went the "pass the access_token back to client" route:
gapi.analytics.auth.authorize({
'serverAuth': {
access_token // received from server, through Ajax request
}
})