The remote server returned an error: (401) Unauthorized in Microsoft.ProjectOxford - azure-cognitive-services

Call GetSentimentAsync is failing with error 401 as mentioned in title
var client = new SentimentClient(Constants.API_KEY);
var request = new SentimentRequest();
var response = await client.GetSentimentAsync(request);
My resource group for generating key in Azure has location "South Central US", my location is Colorado, my subscription is "Visual Studio Enterprise"
I used this page to test my service
https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c7
If I use https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/someID link to test call. It gives 401.
If I use https://southcentralus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/someID/ then it is giving 200.
Seems like issue is related to the Region I selected at the time of creation of New Resource in Azure. Seems like default Region is not what I selected, South Central US
So, what should I do make my call succeed? Where I can mention region in making API call?
Thanks
Abbas

Solved It. I just check what is end point I am hitting from my program using fiddler and it was westus Just create Azure end point with westus region.

Location is in the API call itself: https://[location].api.cognitive.microsoft.com/text/analytics/v2.0/sentiment. In your case, you should use southcentralus in place of [location].
Example of POST request is on this page: https://southcentralus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c9/console.

Related

ADFS 2016 On behalf of flow : cannot get any user informations

I'm trying to implement the "on behalf of" flow in an application using ADFS 2016 as STS. As a reference, I look at this Microsoft tutorial (https://learn.microsoft.com/en-ca/windows-server/identity/ad-fs/development/ad-fs-on-behalf-of-authentication-in-windows-server). It's working as it should, I can login into my web application and then use my original access token in UserAssertion to generate a new access token with the proper audience to call my API BUT I found absolutely no way to include any user informations (sub, name, email, upn etc.) into the access token for my API, even if I set claim rules into my ADFS configurations for the API.
I checked the communication between my app and adfs using Fiddler and everything looks like the informations in the tutorial. See the screen shot of the "on behalf of" request below :
Here's the resulting access token :
Finally, here's the code I use to generate my new access token :
private async Task<string> GetAccessToken(ClaimsPrincipal user, string originalAccessToken)
{
var authority = "[authority]";
var context = new AuthenticationContext(authority, false);
string userName = user.FindFirstValue("upn");
var userAssertion = new UserAssertion(originalAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer",userName);
var cc = new ClientCredential("https://localhost:44387/", "[client_secret]");
var result = await context.AcquireTokenAsync("https://localhost:44339/", cc, userAssertion);
return result.AccessToken;
}
Have you struggle with that scenario and if yes, did you find a way to fix this ?
Thanks
I've only used the Microsoft On Behalf Of flow with Azure AD and not ADFS, but it looks like you need to send a more detailed scope in your User Info request.
Maybe try sending 'openid profile email', to indicate that you want that type of detail, as in Section 17 of my blog post. Of course this assumes that this type of data has been registered for all users.
TROUBLESHOOTING
Looks like one of these will be the cause:
A suboptimal Microsoft library that does not allow you to send the required scope
Or ADFS 2016 perhaps lacks the scope features that work correctly in Azure AD
I would concentrate on making extra sure you are sending the correct form URL encoded request message, using a tool such as curl, Postman or a plain C# HttpClient. Here is the code I used to send the correct scope - using an open source library rather than a Microsoft one:
Sample NodeJS Code
If you can get the scope sent correctly then you should have a resolution either way:
Either you get the correct data and can update your code
Or the behaviour you want is not supported by ADFS
Good luck ...

Getting server error on firebase dynamic link CreateManagedShortLinkRequest with the Ruby client

I am trying to create a dynamic link using the Ruby SDK. I believe I have everything right, but I'm getting a
Google::Apis::ServerError: Server error
When creating the URL
Could you help me figure out what I'm missing/doing wrong or if this is a Google issue ?
Assuming I have generates Oauth credentials requesting the appropriate scopes, I am doing
request = ::Google::Apis::FirebasedynamiclinksV1::CreateManagedShortLinkRequest.new(
dynamic_link_info: ::Google::Apis::FirebasedynamiclinksV1::DynamicLinkInfo.new(
domain_uri_prefix: Rails.application.secrets.firebase_dynamic_link_prefix,
link: campaign.linkedin_url,
),
suffix: ::Google::Apis::FirebasedynamiclinksV1::Suffix.new(
option: 'SHORT',
),
# name: "Linkedin acquisition URL of #{camp.utm_campaign_name} for #{camp.contractor.name} <#{camp.contractor.email}>",
name: "Test of generation",
)
# => <Google::Apis::FirebasedynamiclinksV1::CreateManagedShortLinkRequest:0x000021618baa88
# #dynamic_link_info=#<Google::Apis::FirebasedynamiclinksV1::DynamicLinkInfo:0x000021618bad80
# #domain_uri_prefix="https://example.page.link",
# #link="https://www.example.com/?invitation_code=example&signup=example&utm_campaign=example&utm_medium=example&utm_source=example">,
# #name="Test of generation",
# #suffix=#<Google::Apis::FirebasedynamiclinksV1::Suffix:0x000021618babf0
# #option="SHORT">
# >
link_service.create_managed_short_link(request)
def link_service
#link_service ||= begin
svc = ::Google::Apis::FirebasedynamiclinksV1::FirebaseDynamicLinksService.new
svc.authorization = oauth_service.credentials
svc
end
end
I know OAuth scopes seem to be working as previously I was getting
Google::Apis::ClientError: forbidden: Request had insufficient authentication scopes.
But I fixed it after increasing OAuth scopes to cover firebase. Also, my request seems correct, as when I try to omit one of the parameters (like the name) I'm getting appropriate validation errors like
Google::Apis::ClientError: badRequest: Created Managed Dynamic Link must have a name
My only clue, is that the create_managed_short_link actually takes more parameters. In the example given above, I also have substituted our real firebase prefix by example but I do own the real firebase prefix I am using, and link generation directly from the Firebase frontend console actually works.
I've updates my google sdk to the most recent version up to date
- google-api-client-0.30.3
Unfortunately generating managed short links through the REST API is not currently supported.
As stated here by someone who works(ed) in the dynamic links team itself.
For now we can only use CreateShortDynamicLinkRequest, however this endpoint does not allow to specify a custom_suffix (i.e. https://example.com/my-custom-suffix)

cosmos db, generate authentication key on client for Azure Table endpoint

Cosmos DB, API Azure Tables, gives you 2 endpoints in the Overview blade
Document Endpoint
Azure Table Endpoint
An example of (1) is
https://myname.documents.azure.com/dbs/tempdb/colls
An example of (2) is
https://myname.table.cosmosdb.azure.com/FirstTestTable?$filter=PartitionKey%20eq%20'car'%20and%20RowKey%20eq%20'124'
You can create the authorization code for (1) on the client using the prerequest code from this Postman script: https://github.com/MicrosoftCSA/documentdb-postman-collection/blob/master/DocumentDB.postman_collection.json
Which will give you a code like this:
Authorization: type%3Dmaster%26ver%3D1.0%26sig%3DavFQkBscU...
This is useful for playing with the rest urls
For (2) the only code I could find to generate a code that works was on the server side and gives you a code like this:
Authorization: SharedKey myname:JXkSGZlcB1gX8Mjuu...
I had to get this out of Fiddler
My questions
(i) Can you generate a code for case (2) above on the client like you can for case (1)
(ii) Can you securely use Cosmos DB from the client?
If you go to the Azure Portal for a GA Table API account you won't see the document endpoint anymore. Instead only the Azure Table Endpoint is advertised (e.g. X.table.cosmosdb.azure.com). So we'll focus on that.
When using anything but direct mode with the .NET SDK, our existing SDKs when talking to X.table.cosmosdb.azure.com endpoint are using the SharedKey authentication scheme. There is also a SharedKeyLight scheme which should also work. Both are documented in https://learn.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services. Make sure you read the sections specifically on the Table Service. The thing to notice is that a SharedKey header is directly tied to the request it is associated with. So basically every request needs a unique header. This is useful for security because it means that a leaked header can only be used for a limited time to replay a specific request. It can't be used to authorize other requests. But of course that is exactly what you are trying to do.
An alternative is the SharedKeyLight header which is a bit easier to implement as it just requires a date and the a URL.
But we don't have externalized code libraries to really help with either.
But there is another solution that is much friendly to things like Fiddler or Postman, which is to use a SAS URL as defined in https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/12/introducing-table-sas-shared-access-signature-queue-sas-and-update-to-blob-sas/.
There are at least two ways to get a SAS token. One way is to generate one yourself. Here is some sample code to do that:
var connectionString = "DefaultEndpointsProtocol=https;AccountName=tableaccount;AccountKey=X;TableEndpoint=https://tableaccount.table.cosmosdb.azure.com:443/;";
var tableName = "ATable";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference(tableName);
await table.CreateIfNotExistsAsync();
SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(1000),
Permissions = SharedAccessTablePermissions.Add
| SharedAccessTablePermissions.Query
| SharedAccessTablePermissions.Update
| SharedAccessTablePermissions.Delete
};
string sasToken = table.GetSharedAccessSignature(
policy, null, null, null, null, null);
This returns the query portion of the URL you will need to create a SAS URL.
Another, code free way, to get a SAS URL is to go to https://azure.microsoft.com/en-us/features/storage-explorer/ and download the Azure Storage Explorer. When you start it up it will show you the "Connect to Azure Storage" dialog. In that case:
Select "Use a connection string or a shared access signature URI" and click next
Select "Use a connection string" and paste in your connection string from the Azure Portal for your Azure Cosmos DB Table API account and click Next and then click Connect in the next dialog
In the Explorer pane on the left look for your account under "Storage Accounts" (NOT Cosmos DB Accounts (Preview)) and then click on Tables and then right click on the specific table you want to explore. In the right click dialog you will see an entry for "Get Shared Access Signature", click on that.
A new dialog titled "Generate Shared Access Signature" will show up. Unfortunately so will an error dialog complaining about "NotImplemented", you can ignore that. Just click OK on the error dialog.
Now you can choose how to configure your SAS, I usually just take the defaults since that gives the widest access permission. Now click Create.
The result will be a dialog with both a complete URL and a query string.
So now we can take that URL (or create it ourselves using the query output from the code) and create a fiddler request:
GET https://tableaccount.table.cosmosdb.azure.com/ATable?se=2018-01-12T05%3A22%3A00Z&sp=raud&sv=2017-04-17&tn=atable&sig=X&$filter=PartitionKey%20eq%20'Foo'%20and%20RowKey%20eq%20'bar' HTTP/1.1
User-Agent: Fiddler
Host: tableaccount.table.cosmosdb.azure.com
Accept: application/json;odata=nometadata
DataServiceVersion: 3.0
To make the request more interesting I added a $filter operation. This is an OData filter that lets us explore the content. Note, btw, to make filter work both the Accept and DataServiceVersion headers are needed. But you can use the base URL (e.g. without the filter parameter) to make any of the REST API calls on a specific table.
Do be aware that the SAS token is scoped to an individual table. So higher level operations won't work with this SAS token.

I have registered app_id and app_key giving me this "error"Unauthorized","error_description":"Unauthorized. Th

for HERE REST api I have registered app_id and app_key and appended them in url but it is giving me this "error"Unauthorized","error_description":"Unauthorized. The request is not from an authorized source "
Also, the FAQs page mentions the following:
How do I generate an app_id and app_code for my application?
To generate an app_id and app_code for an application, you need to
sign in then go to https://developer.here.com/plans to select and
register for the appropriate plan.
At the final step in the registration process, an app_id and app_code
is automatically generated for your application.
Please note, it can take up to an hour for a new app_id to be whitelisted against all services.
So if you had just created your credentials when you got this error, you may want to try again.
Looking back at the error I received when I attempted to access the API, however, I got the following response:
{"details":"invalid credentials for I5zJljd5cZyOx5SyROKT","additionalData":[],"type":"PermissionError","subtype":"InvalidCredentials"}
So it may be that Jason's comment above is more appropriate but I'll leave this answer for other users who may come searching after creating new credentials.
A good way to check your credentials would be to make a valid URL call to any of the REST APIs - e.g. the Geocoder API: https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext=London&app_id={YO‌​UR_APP_ID}&app_code={YOUR_APP_CODE} - it gives an error response for an invalid pair.
As mentioned in the answer : Need separate credentials for WSE API? - you may need to request additional access for the HERE Platform extensions
selfservesupport#here.com here is the support. Describe ur problem and attach an snapshot where you get error at what request. (URL)

Access all gmail contacts using access_token in asp.net

I'm trying to access gmail contacts in asp.net web application.
Still I'm able to get access_token from google, but when I send this acccess_token to google contact api, its giving me error.
Below is the url where I redirect from my application and user authenticates by giving his email and password.
https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri=http://localhost:3223/WebSite1/Default.aspx&response_type=token&client_id=881595232473.apps.googleusercontent.com
After this user came back to my web application with access token.
Here I've used two diferent methods to get all contacts:
Method 1 - Web Request:
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();
System.IO.Stream ReceiveStream1 = response1.GetResponseStream();
StreamReader readStream1 = new StreamReader(ReceiveStream1);
string result = readStream1.ReadToEnd();
Its working fine and gives me result in XML. But problem is that its giving only first 25 contacs while i've total 246 contacts.
Method 2 - Google Contact API:
RequestSettings rs = new RequestSettings("aman contact", Request.QueryString["access_token"].ToString());
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
PrintAllContacts(cr);
Feed<Contact> f = cr.GetContacts();
Here its giving me following error:
Execution of request failed: http://www.google.com/m8/feeds/contacts/default/full
after this it shows me a yellow page with following error:
The remote server returned an error: (401) Unauthorized.
I can only comment on your question about Method 1 - Web Request, since I haven't used .Net to integrate with Google Contacts API.
I suggest that you try passing in a value for max-query (it is 25 by default). In my experience pulling about 500 contacts from the api takes less than one second, so you should be able to safely query you particular address book in one shot. However, you should tune this value to your application's requirements. For example, if you need your application to be very responsive, you may want to make this value smaller, so you can start to populate the contacts faster. If you are doing this work in the background, then waiting 5 seconds for 5000 contacts may be acceptable.
Because people had widely varying sizes of address book, you need to be able to query the API multiple times using the start-index parameter. After the first query, take a look at the values returned here:
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
total-results will let you compute how many times you'll need to query with a different start-index to get all the data.
The Google Contacts API (v3) describes these parameters. As a word of warning, start-index is a 1 based index into the array of contacts, not a page index, so you have to do the math. For example, you would request max-query=25&start-index=26 to access page 2 of the contacts.

Resources