i have a error 401 with microsoft emotion api in java - microsoft-cognitive

im using the example code to call the emotions api but i have an error 401 and i cannot identify the error
the result: { "error": { "code": "Unauthorized", "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." } }
HttpClient cliente = HttpClients.createDefault();
String key ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
try{
URIBuilder builder= new URIBuilder("https://api.projectoxford.ai/emotion/v1.0/recognize");
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-type","application/json");
request.setHeader("Opc-Apim-Subscription-Key",key);
StringEntity reqEntity = new StringEntity("\"url\": \"http://am-elsalv-cdn.agilecontents.com/resources/jpg/5/3/1458595472835.jpg\"");
request.setEntity(reqEntity);
HttpResponse response = cliente.execute(request);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println(EntityUtils.toString(entity));
}
}catch(Exception e){
System.out.println(e.getMessage());
}

The 401 error is typically shown when you’re using an invalid subscription key to call our APIs. This could happen for a number of reasons:
Incorrect key as result of a copy/Paste error when pulling the key from http://www.microsoft.com/cognitive-services/en-us/subscriptions. Additionally, make sure there are no leading or trailing spaces in your key (it doesn’t look like it from your code, but calling out for completeness).
If your key was working before and now is no longer working, you could be out of your monthly quota (number of calls) or trying to make calls too quickly for the TPS (transactions per second) supported for your key. You can check the status of your key by going to the subscriptions page, finding the emotion subscription, and clicking “Show quota”.
There is a service interruption currently on-going. If you think this is the case, please let us know through tickets#cognitive.uservoice.com.
If you’ve tried all of these things and are still experiencing issues, try to make an API call using your subscription key through our testing console. If this still fails, regenerate your key through the subscriptions page by finding the Emotion API, identify the key column, and clicking “Regenerate” under the key that is not working. Note that you’ll have to update all references to your old key as this will completely invalidate it in favor of the newly generated key.

Related

REST API Getting 401 UnAuthorized

I am using .NET Core Web API to make call and getting back
401, unauthorized ? I am using a REST API key.
var ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var _Http = new HttpClient();
var response = await _Http.GetAsync($"https://geocode.search.hereapi.com/v1/geocode?q={address},{city},{state},{postalCode},{country}&apikey={ApiKey}");
What am I missing ?
I am getting the key from the following section
UPDATE: this problem has vanished today. It appears to have been a bug on the Here side.
Yesterday: My JS API code, which has been working fine, is throwing 401s today as well, with no changes. I could kill the project and create a new one with a new API key, but I'm not sure that would fix it. I did find that it was "disabled" (due to a billing issue, I think), and I "enabled" it and it still throws 404s.
Did you confirm your email address (by clicking the link in the email they send)?
If you have not confirmed your email address, then the API Key is only valid for 30 minutes.

Fetching messages from empty channel results in 403 in Microsoft Teams

I'm having issues with extracting channel messages from a Microsoft Team. I have a javascript app that crawls through all Teams in a organization and extract the number of messages from all channels in all the teams. It works wonderfully in that it return the correct amount of messages, the problem is that when the app try to fetch a message from a channel where no one have made a message in the channel there is an HTTP error with the ErrorCode 403 (forbidden). Even though the app is successful in that it delivers on what it is supposed to do, I can't have an application that sends 50 angry, red messages every time it makes a http call.
The call I am using is the following
https://graph.microsoft.com/beta/teams/{teamID}/channels/{channelID}/messages
Does anyone know if this is solvable? If not is it possible to check if a channel is empty? And if that is not an option; is there anyone to hide those dirty error messages from the console?
Edit #1
To call to the api I used:
let header = new Headers();
header.append("Authorization", "Bearer " + accessToken);
header.append("Content-Type", "application/json");
fetch("https://graph.microsoft.com/beta/teams/232808c2-d500-47b0-9ead-e238c5e2ab95/channels/19:69a01be632994d123014bbae1aa5db1e#thread.tacv2/messages", {method:"GET", headers: header})
Edit #2
I response object seems to be correct:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#teams('90baabba-1b5e-471c-a163-8a9b4b680de7')/channels('19%3A01c741f599e547f0b9b38296283b7fec%40thread.skype')/messages",
"#odata.count": 0,
"value": []
}
The problem is that in when I look in Google Chrome > Dev tools > Console, the fetch still displays the error:
GET https://graph.microsoft.com/beta/teams/4f460179-4691-42e5-8677-9101dcdb65fe/channels/19:3497f5b8f9f54149919631b32d21e608#thread.tacv2/messages 403 (Forbidden)
And when I console log the error it just displays as:
error: {code: "Forbidden", message: "Forbidden", innerError: {…}}
Only team members are allowed to read messages. Admins can do team management i.e. CRUD operations on teams, channels, tabs etc. They however cannot read messages. This is intentional and we do not have plans to change this in near future

Yahoo OAuth Invalid Client ID

I'm trying to connect my ASP.NET Core 3.1 web app with Yahoo. To do this, I have to set up Authorization with OAuth. I have followed a few different guides, including:
https://developer.yahoo.com/oauth2/guide/openid_connect/getting_started.html
https://www.yogihosting.com/implementing-yahoo-oauth-2-0-in-csharp-and-asp-net/
I have set up my app in Yahoo, with the configuration found in the below picture:
I then have my code set up to send the authorization request to Yahoo with the following code:
public void YahooAuth()
{
string id = configuration["YahooClientId"];
string returnUrl = "https://www.fantasysimmer.com/FootballSimulator/Sim";
string url = $"https://api.login.yahoo.com/oauth2/request_auth?client_id={id}--&response_type=code&redirect_uri={returnUrl}";
Response.Redirect(url);
}
When this code is ran however, I get an error page with a message "Developers: Please specify a valid client and submit again.", and the URL displays:
https://api.login.yahoo.com/oauth2/error?client_id={Client_ID}--&error=unauthorized_client&error_description=invalid+client+id
I double and triple checked the Client ID, and the client ID in the URL is the same as in my Yahoo App's profile. I'm wondering now, is there an extra step that I missed in registering my app, or is there something wrong with my code?
Edit: Progress is made! The dashes after the client id must have been part of the example, or otherwise were an error. When I removed that, I started getting a new error, saying to enter in a valid request. It had something to do with my return url, because replacing that with 'oob' made it go through.
So there were two errors. The first was that the "--" after the client id were not supposed to be there. I'm not sure why in yahoo's example they have them there, but they aren't needed. The second reason is that my return uri was capitalized in my code, but not capitalized in my app settings. Now it works!

Firebase push notifications always arrive as an empty message

I have been trying to get push notifications working using firebase. So far I have got as far as successfully sending an empty message "tickle". The problem is adding the message payload seems to have no affect on what the client receives. That is the service worker just sees it as another empty message.
I started by going through googles guide here - https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
After going through how to send an empty message it says the message payload must be encrypted and suggests using an existing library to do it. To quote - "As with anything related to encryption, it's usually easier to use an actively maintained library than to write your own code".
I tried to use web-push-php which is one of the libraries recommended by googles guide. After having trouble with that i discovered web-php-push doesn't actually support firebase.
Looking on here i find examples that look really simple and don't event encrypt the message payload. It is simply sent in plain json. Doing this has no affect and the receiving end still thinks it's an empty message. See my code below.
I am at a complete loss with this and i'm confused why googles guide says the message data must be encrypted but there are countless examples on SO where it is just send in plain json text.
This is what i am posting from my server to the end point.
POST https://fcm.googleapis.com/fcm/send Authorization: key=[my server
key] Content-Type: application/json {"priority":10,"to":"[subscriber
id]","notification":{"body":"test body","title":"test title"}}
Here is my event listener in my service-worker.js
self.addEventListener('push', function(e) {
var body;
if (e.data) {
body = e.data.text();
} else {
body = "No message "+JSON.stringify(e);
}
var options = {
body: body
};
e.waitUntil(
self.registration.showNotification('Launtel Residential', options)
);
});
When i run the post request above the push notification occurs and triggers the service worker 'push' event as expected but no message data is present. e.data returns null. The 'e' object always just contains a flag set to true. e.isTrusted==true

Meteor.user() on iron-router server side

How can check, on server side route, if user is logged?
I would add check on 'before', but Metor.user() don't work here.
thanks in advance.
p.s. I have found How to get Meteor.user() to return on the server side?, but not work on iron-router
I'm afraid that this is not possible. I guess that the problem comes from the fact that you're trying to connect to the server with two different protocols - both literally and in logically - so there is no obvious way to relate this two actions.
There is, however, a pretty simple solution that may suit your needs. You'll need to develop a simple system of privileges tokens, or secret keys, or whatever you call them. First, create a server method
var Secrets = new Meteor.Collection("secrets"); // only on server!!!
Meteor.methods({
getSecretKey: function () {
if (!this.userId)
// check if the user has privileges
throw Meteor.Error(403);
return Secrets.insert({_id: Random.id(), user: this.userId});
},
});
Then, you can now use it on the client to get the secretKey which attach to your AJAX request (or something), either within the HTTP header or in the URL itself. Fear not!
They will all be encrypted if you're using HTTPS.
On the server side you can now retrieve the secretKey from the incoming request and check if it is present in the Secrets collection. You'll know then if the user is granted certain privileges or not.
Also you may want to remove your secret keys from the collection after some time for safety reasons.
If what you're looking to do is to authenticate the Meteor.user making the request, I'm currently doing this within the context of IronRouter.route(). The request must be made with a valid user ID and auth token in the header. I call this function from within Router.route(), which then gives me access to this.user:
###
Verify the request is being made by an actively logged in user
#context: IronRouter.Router.route()
###
authenticate = ->
# Get the auth info from header
userId = this.request.headers['x-user-id']
loginToken = this.request.headers['x-auth-token']
# Get the user from the database
if userId and loginToken
user = Meteor.users.findOne {'_id': userId, 'services.resume.loginTokens.token': loginToken}
# Return an error if the login token does not match any belonging to the user
if not user
respond.call this, {success: false, message: "You must be logged in to do this."}, 401
# Attach the user to the context so they can be accessed at this.user within route
this.user = user
###
Respond to an HTTP request
#context: IronRouter.Router.route()
###
respond = (body, statusCode=200, headers={'Content-Type':'text/json'}) ->
this.response.writeHead statusCode, headers
this.response.write(JSON.stringify(body))
this.response.end()
This code was heavily inspired by RestStop and RestStop2. It's part of a meteor package for writing REST APIs in Meteor 0.9.0+ (built on top of Iron Router). You can check out the complete source code here:
https://github.com/krose72205/meteor-restivus

Resources