Access denied due to invalid subscription key - azure

I have used the Crossref REST API where I just send it a query in a browser address bar, which then returns results in JSON.
So I send the following URL:
https://api.crossref.org/works?query.bibliographic=Randomized trial of intensive early intervention for children with pervasive developmental disorder&query.author=Groen&rows=1
I was hoping to so the same with the Microsoft REST API, but if I send it:
I get "Access denied due to invalid subscription key".
Can I pass my key via the URL? If so how?
Or is it not that simple.
Does it need other code as well - I can code in PHP if needed, or use jQuery.
Something like:
$(document).ready(function() {
$.ajax({
type:'GET',
url:'https://api.crossref.org/works?query.bibliographic=<?php echo $title ?>&query.author=<?php echo $author ?>&rows=1&select=is-referenced-by-count,author,title,DOI,issn-type,volume,issue,link,page,abstract',
success:function(result) {
var total_results = result.message["total-results"];
}
});
But again, with the Microsoft API - how would I send it the keys?
Thank you.

What is "the Microsoft REST API"? Do you mean Azure API Management? "Invalid subscription key" implies that this is an API hosted in API Management which uses this term to describe its authentication model. The following answer assumes this is the case.
You would need to be registered as a user and be given a subscription key. There is a self-service portal for doing this, which is described by this documentation. It is up to the API's administrator whether you are permitted to self-service or not, so you may or may not be able to do this yourself, or you may have to request the administrator to register you. Further documentation describes a bit how to use the portal.
When you have it, you would apply it as an http header named Ocp-Apim-Subscription-Key, but the name it expects is also configurable and may have been changed, which the administrator would have to tell you.

I finally found the documentation for what I needed (the Microsoft documentation around Azure is a horrendous maze with a lot of stuff that is outdated and broken).
So the documentation is here:
https://msr-apis.portal.azure-api.net/docs/services/academic-search-api/operations/565d753be597ed16ac3ffc03?
I modified the Jacascript example at the bottom of page and came up with:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type:'GET',
url:'https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr=Composite(AA.AuN==%27jaime%20teevan%27)&count=2&attributes=Ti,Y,CC,AA.AuN,AA.AuId',
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","xxxxmykeyxxxxx");
},
success:function(result) {
alert(result.entities[0].Ti);
}
});
});
</script>
</head>
</html>
The query returns all the titles for the author "jamie teevan".
Though in this example I am just outputting the first title via 'alert'. I haven't coded the rest of it yet - just wanted to know if it worked or not at this point.
Now all I need to do is work out the expression to return all the citing documents for a given title + author!! :-/ wish me luck.

Related

Authenticating a REST request in an Excel Add-in

I am trying to develop an add-in for Excel with the goal that it will create calendar events based on data inside a spreadsheet.
I can do almost everything that I want except use the REST API to build the events in the calendar and I can't exactly figure out where I went wrong.
I have followed the documentation suggested by #MarcLaFleur.
I can build and run the application no problem, but when I click on the 'Get my files from OneDrive' button, I get the following:
Code: 5001
Message: An internal error has occurred.
name: Internal Error
This is coming from the program.js file in the public directory somewhere in the else clause of this function.
function getDataWithoutAuthChallenge() {
Office.context.auth.getAccessTokenAsync({ forceConsent: false },
function (result) {
if (result.status === "succeeded") {
// TODO1: Use the access token to get Microsoft Graph data.
accessToken = result.value;
getData("/api/onedriveitems", accessToken);
}
else {
console.log("Code: " + result.error.code);
console.log("Message: " + result.error.message);
console.log("name: " + result.error.name);
document.getElementById("getGraphAccessTokenButton").disabled = true;
}
});
}
Here are the scopes in my manifest.xml
...
<WebApplicationInfo>
<Id>c931b396-7 ... </Id>
<Resource>api://localhost:3000/c931b396-7 ... </Resource>
<Scopes>
<Scope>files.read.all</Scope>
<Scope>profile</Scope>
</Scopes>
</WebApplicationInfo>
</VersionOverrides>
And here are the scopes on apps.dev.microsoft.com:
If you can shed any light for me, it would really help me out.
5001 can be caused by not requesting profile scope. You need to request the profile scope in addition to Calendar.ReadWrite. You do this when you register the app, as well as in the manifest. For more information, see the articles that Marc LaFleur linked to.
The 5001 error often suggests something fundamentally wrong with the add-in API in Office. For example, your Office app doesn't support the API, the manifest is incorrect, or the version of office.js doesn't work with it. Since you're using the sample, two things come to mind:
You aren't running the latest Insiders
build
The wrong manifest is getting loaded (this sometimes happens if you're
on Windows and using a version of Visual Studio 2017 that has old
schema files, so you have to do a post-build clean up of the debug
Manifest XML)
Your manifest and Azure registration look mostly good, though Rick's comment about Scopes is relevant. profile must work with openid as a pair (profile alone won't work; openid alone won't work), and as discussed you need this consented. As the developer, you can try consenting for yourself at the protocol level. You’ll want to update the client_id, redirect_uri, and scope query parameters as appropriate, and add &prompt=consent.
To answer a later question, Excel and Mail add-ins are different, and my answer only applies to Excel. For Outlook there's a different sample.
The documentation can be found at Enable single sign-on for Office Add-ins. There is also walk though for both ASP.NET and Node.js as well documentation on Troubleshooting.
There are a number of things that could be going wrong here but without knowing more about your registration it is difficult to determine. That said, here are a couple of common mistakes:
You'll need to make sure you receive Admin Consent for the tenant you're developing against. This is only a dev requirement and won't be required once your publish to the Store.
Make sure you've pre-authorized the correct applications. You'll need pre-authorizations for:
d3590ed6-52b3-4102-aeff-aad2292ab01c (Microsoft Office)
57fb890c-0dab-4253-a5e0-7188c88b2bb4 (Office Online)
bc59ab01-8403-45c6-8796-ac3ef710b3e3 (Office Online)
Make sure the scopes you're defining in your manifest.xml are reflected in the app registration at apps.dev.microsoft.com.
If you make changes to your permission scopes, you need to make sure you repeat the Admin Consent process. When you receive consent, they are consenting to the scopes that were registered at the time of consent rather than the App ID itself.

How to get Correct Subscription key for microsoft Face API for Nodejs?

I am using project-oxford inorder to use Microsoft API with nodejs. I am keep on getting error that ,
{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}
{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}
I have also regenerated my subscription key for my microsoft account and tried to access the code. Still I am getting the same issue. Spent lot of time to find my bug fixed, But I couldn't able to solve.
This is my nodejs code,
var oxford = require('project-oxford'),
client = new oxford.Client({SubscriptionKey});
client.video.trackFace({
url: path,
}).then(function (response) {
console.log('Response ' + JSON.stringify(response));
},function (error) {
console.log("Error"+JSON.stringify(error));
});
Please guide me to fix this issue.Thanks in Advance!!
You can obtain a key via the Microsoft Cognitive Services web site.
From what I can gather, you are using https://github.com/felixrieseberg/project-oxford, is that correct?
It seems that project requires one subscription key, which then is used for all API calls. I can't see any reasons it shouldn't work, if you have signed up for the subscription key for the Video API.
Given that the library you're using is built the way it is, it seems to me that you will only be able to use one API at the time, doing it the way you're doing it now.
Am I making any sense?
Actually Now I am getting output for the same code excepting that I was not able use the localhost URL [i.e., http://localhost:3000/uploads/img.jpg]. While using the url of webserver only then I am getting the output!!
Can anyone explain me the complete fact. i.e., I need to know whether I cannot use the localhost url. If I use so I am getting the error which I have posted in this question.

Instagram API: The access_token provided is invalid

I have registred a sandbox user. Now I am trying to use it, but I recieve "The access_token provided is invalid".
Sample request:
https://api.instagram.com/v1/users/searchq=abc&count=2&client_id=7b67cff1a7ab462881298434c08b5ab8
It was working in live mode, but I can't find why it isn't working in sandbox.
You need to check for requirements Scope for API you are using and if it's need and Authentications "Valid access Token". where also had some changes.
basic - to read a user’s profile info and media
public_content to read any public profile info and media on a user’s behalf
follower_list to read the list of followers and followed-by users
comments - to post and delete comments on a user’s behalf
relationships - to follow and unfollow accounts on a user’s behalf
likes - to like and unlike media on a user’s behalf
And take look about **Sandbox API behavior of your application not life yet :**
API Behavior
The behavior of the API when you are in sandbox mode is the same as when your app is live, but comes with the following restrictions:
Data is restricted to sandbox users and the 20 most recent media from each sandbox user
Reduced API rate limits
The first point is important and it means that the API behaves as if the only users on Instagram were your sandbox users, and the only media ever posted were the last 20 for each of these users.
For example, if you query the /users/{user-id}/ endpoint and the {user-id} is a sandbox user, then you will get the normal API response; but if the {user-id} is not a sandbox user, you will get a APINotFound error.
Good luck
For me the access token Instagram generate is too short: they gave me something like this:
d2c387d768ec4d619306807c53bbf92b
it should be:
2940736713.1677ed0.31bb22b2b0f84befacc79c6afd025134
I used this site to generate it:
http://instagram.pixelunion.net
I found it when solving the same problem with access by access_token
Here is official faq how to get access_token
You just should go through following steps (link to Instagram API documentation https://www.instagram.com/developer/authentication/):
1.Request the CODE
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
change CLIENT_ID to you client id (you could get it here https://www.instagram.com/developer/clients/manage/ )
change REDIRECT-URI to your redirect_uri from tab security in client settings(open link above and tap to 'manage' button). I Used this one https://meyerweb.com/eric/tools/dencoder/ Encode url here and paste te result instead REDIRECT-URI
After you prepared it cope ready link to adress bar in your browser and run
2. Get the CODE
Browser ask you a premissons and redirect you to callback url with the code in the end. It will be look like this in adress bar:
http://yoursite.some/?code=d8af5619af6853d4ad11b4dd5f1ef17e
In this example your code is d8af5619af6853d4ad11b4dd5f1ef17e
Save it. You should use it in access_token request below
3. Make an access_token request
Open terminal and use curl:
curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
Change CLIENT_ID, CLIENT_SECRET, AUTHORIZATION_REDIRECT_URI and CODE to your own data and run it.
Curl return you JSON with access_token like this:
{
"access_token": "fb2e77d.47a0473320504cb3ab4a1f626d174d2d",
"user": {
"id": "1576583",
"username": "some",
"full_name": "Some",
"profile_picture": "..."
}
}
Well done! In this example fb2e77d.47a0473320504cb3ab4a1f626d174d2d is your access_token. Copy access_token value, use it in your app and enjoy you coding! :)
My issue was using v1 of Instafeed.js, rather than v2.
Once I switched to v2, everything started working.
<script src="/instafeed/dist/instafeed.min.js"></script>
<script src="https://ig.instant-tokens.com/users/.../instagram/.../token.js?userSecret=..."></script>
<div id="instafeed" class="instagram-feed">
</div>
<script>
(function(){
console.log(InstagramToken);
window.addEventListener('load', function () {
var feed = new Instafeed({
accessToken: InstagramToken,
});
feed.run();
});
})();
</script>
You haven't specified an access_token for your request.

Incontext Paypal Integration- without moving away from site [Nodejs, Expressjs]

I am using nodejs and expressjs and using "paypal-ec" node package to do incontext paypal integration.
This is invoked with the following piece of code:
<script src='https://www.paypalobjects.com/js/external/dg.js' type='text/javascript'></script>
<script>
var dg = new PAYPAL.apps.DGFlow(
{
trigger: 'paypal_submit',
expType: 'instant'
});
</script>
What I have achieved with this
I am able to make payment in the Paypal Sandbox environment but it shows me older payment screen where in user needs to fill in the details of address etc (I am not able to attach screenshot because of credits)
What I want to achieve
I am trying to make payment with the screens where in user doesn't need to prefill any data also it gives better UI.
Some experience like provided in this plukr link http://plnkr.co/edit/3vfNSVRyq86pDR5mH4HH?p=preview
The problem with the given piece of code in plunk is that it doesn't expose what is there in the action method and how can I provide amount to it (or any other details if any).
Any kind of help is appreciated.
I get it but don't claim to be a node dev - yet :) so this is "conceptual":
At the end of the day, the server-side call (SetExpressCheckout) where you send your trnx details (items, price, return/cancel urls, etc.) to Paypal and obtain a token is unchanged (with the documented limitations and ignored params that is).
The change is in the front-end where:
the in-context js script<script async src="//www.paypalobjects.com/api/checkout.js"></script>
new redirect url : https://www.paypal.com/checkoutnow?token=[the token you obtained]
are in play
The linked sample's server-side SetExpressCheckout process is the:
http://166.78.8.98/cgi-bin/aries.cgi?sandbox=1&direct=1&returnurl=http://166.78.8.98/cgi-bin/return.htm&cancelurl=http://166.78.8.98/cgi-bin/cancel.htm
You can see the returnurl and cancelurl set (but it could have been done server side as well). This will obtain the token which is needed for the subsequent steps.
If you can inspect the traffic, you'll see the response where the redirect (that is "caught" in the front end and displayed "in-context"):
HTTP/1.1 302 Found
Date: Sun, 05 Jul 2015 16:00:48 GMT
Server: Apache/2.4.7 (Ubuntu)
Access-Control-Allow-Origin: *
Location: https://www.sandbox.paypal.com/checkoutnow?useraction=commit&token=EC-94X58918K2362702E&ul=0
This sample is probably more detailed and "less magical" (shows more of what's going on) and is what helped me implement:
http://plnkr.co/edit/UhNka4VaaRRGY1TK32LE?p=preview
Hth.

403 when trying to list web spaces via Azure websites management REST API

I'm just in the process of experimenting with the Azure rest api's in preparation for some work I'm heading into...
Within node.js I'm trying to obtain a list of webspaces hosted by my subscription using the following code...
var websiteOptions = {
hostname: 'management.core.windows.net',
path: '/<<Subscription-ID>>/services/webspaces',
method: 'GET',
pfx: new Buffer(managementCert, 'base64'),
strictSSL: true,
headers: {
'x-ms-version': '2013-06-01'
}
};
websiteOptions.agent = new https.Agent(websiteOptions);
var request = https.request(websiteOptions,function(res){
console.log('Status Code:', res.statusCode);
console.log('Headers:', res.headers);
When executed it returns back with..
<Error xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Code>AuthenticationFailed</Code>
<Message>The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
</Message>
</Error>
The strange thing is that if I replace ..
/<<subscription-ID>>/services/webspaces
with...
/<<subscription-ID>>/services/hostedservices
That specific call works like a charm, returning a list of hosted services - so this leads me to believe that I'm encoding/attaching my management certificate correctly.
I have tried various api versions in the headers without much luck, I have also read various sections of this article without much luck.
So why are my credentials working in one section of the API and not the websties section
What am I missing, I'm sure it's something really simple :|
OK so now I feel daft, and it just goes to show that even big companies can get it wrong..
I have been playing a bit more and decided to drop a forward slash onto the end of the API call for the web spaces endpoint.. and...
Bingo... it worked like a treat!!!
Would have been nice if Microsoft was consistent across it's API endpoints, the hosted services end point for instance didn't need this trailing slash.
Also, accurate error messages would have been nice too, instead of just reporting an invalid credentials exception!!!
As always.. the simple things in life :(

Resources