FCM error results - refer error to token - node.js

when sending push messages through fcm (through nodejs firebase admin sdk), getting this error structure:
{
"results": [
{
"error": {
"code": "messaging/invalid-registration-token",
"message": "Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM."
}
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 1,
"successCount": 0,
"multicastId": SOME_ID
}
Is the index of the results relates to the index of the token array that was sent to firebase?

Yes, as described here:
results Array of objects representing the status of the messages processed. The objects are listed in the same order as the request (i.e., for each registration ID in the request, its result is listed in the same index in the response).

Related

Revenuecat Webhook Issue

I have implemented webhook for revenuecat in .net core C#. But for some reason I am getting 400 badrequest with empty response. I am mostly sure that I am not getting the json response in webook through revenuecat for any of the event occurring.
I have also added endpoint on revenue cat webhook with authentication. I have tried several time and as I have not way to test this on local machine. I need help from revenue cat team to provide some reference doc with sample implementation just to get proper json response. Below is the code snippet that I am using to get json response from the webhook endpoint added in revenuecat.
var webHookSecret = _configuration[Constants.RevenueCatWebHookSecret]; var headerAuthorization = HttpContext.Request.Headers["Authorization"].ToString(); #region Check authorization if (webHookSecret == headerAuthorization) { json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); } else { _logger.Information($"Un-Authorized token access in revenuecat webhook. Returning BadRequest response."); throw new APIException(HttpStatusCode.Unauthorized, new APIError(_configuration, "InternalServerError")); }

Microsoft Graph API, DELETE request response Error code 403 ""Access is denied. Check credentials and try again."

I am working on a Microsoft Graph API app where i want to delete email messages from the inbox.
I do that by first getting the emails, putting the id from each email in an array and for each id in that array making a delete request to remove it from the inbox.
When I try and run my code i get the error
Error: Server responded to *request link* with status code 403:
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again.",
"innerError": {
"request-id": "*request id*",
"date": "2020-06-03T09:12:06"
}
}
}
When making the delete request I pass in the same Access Token that i use to make the get request for getting the email data.
Here is my code:
// This is only the code for the delete request, passing the Access Token works aswell as passing the IDList array. It loops trough all the id's and tries to make a request. But the request fails
removeEmail(IDList, AccessToken);
function removeEmail(idList, accessToken) {
idList.forEach(ID => {
var deleteEmails = request('DELETE', `https://graph.microsoft.com/v1.0/me/messages/${ID}`, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
deletedEmails = JSON.parse(deleteEmails.getBody('utf8'));
console.log(deleteEmails);
});
}
How can this be fixed so that it removes the messages from the inbox without any problems?
Thanks in advance!
What permissions have you added to your Microsoft Graph API app?
Deleting an email requires Mail.ReadWrite - https://learn.microsoft.com/en-us/graph/api/message-delete?view=graph-rest-1.0&tabs=http
On the other hand, getting a list of messages works with the following permissions - Mail.ReadBasic, Mail.Read, Mail.ReadWrite - https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0&tabs=http#permissions
To be able to both read and delete email messages, you need Mail.ReadWrite added to your app.

Azure DevOps REST API call to Accounts-endpoint retrieves TF400813 error

I'm trying to read all accounts my user is associated with. The Documentation claims that this should be possible by calling:
GET https://app.vssps.visualstudio.com/_apis/accounts?api-version=5.1
Because the docs are kind of confusing it could be that I have to call
GET https://app.vssps.visualstudio.com/_apis/accounts?ownerId={GUID}&api-version=5.1
instead.
I'm using OAuth-Authentication. In order to get it work I created an ASP.NET Core application. I created an app registration in DevOps and I retrieve an OAuth token with the following scopes without any problem:
vso.auditlog
vso.connected_server
vso.dashboards
vso.entitlements
vso.environment_manage
vso.graph
vso.identity
vso.loadtest
vso.machinegroup_manage
vso.memberentitlementmanagement
vso.profile
vso.project
vso.securefiles_read
vso.security_manage
vso.taskgroups_read
vso.tokenadministration
vso.tokens
vso.variablegroups_read
vso.wiki
According to the docs only vso.profile should be necessary for this request.
However the result I receive is always:
HttpRequestException: Response status code does not indicate success: 401 (TF400813: The user '{AZURE_TENANT_ID}\{MY_MAIL_ADDRESS}' is not authorized to access this resource.).
Other requests are working just fine e.g.:
GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.1
The accounts-request is special because it can be sent without setting the context to a specific organisation or project. I guess this the reason for the different results.
EDIT
After trying ot today using the both URLs mentioned above I now get 400 as the response status code. This is a sample Bearer-Token I got after I decoded it:
{
"nameid": "1340eb0b-cabf-476c-a950-a070c34ca367",
"scp": "vso.profile",
"aui": "a2d8bdf0-9406-415a-aa79-bee9e2600c37",
"appid": "e1bea2a2-****-****-****-************",
"iss": "app.vstoken.visualstudio.com",
"aud": "app.vstoken.visualstudio.com",
"nbf": 1587395030,
"exp": 1587398630
}
Here is some simplified C# code I use:
HttpClient client = _clientFactory.CreateClient("DevOps");
var token = await _authHelper.GetTokenAsync(tokenType);
client.DefaultRequestHeaders.Add("Authorization", $"Bearer { token.AccessToken}");
var uri = "https://app.vssps.visualstudio.com/_apis/accounts?api-version = 5.1";
try
{
var response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
// ex.Message = Response status code does not indicate success: 400 (Bad Request).
// ...
throw;
}

Azure Microsoft Graph API - Subscription - validation request failed

I try to set up a notification for changes in Azure user data (https://learn.microsoft.com/en-us/graph/webhooks).
I send a request from a local client to the Azure Graph API and I have a publicly available server (with SSL) in the payload of the request as notification URL.
Azure now sends a posts request to my server (like in the documentation - exact post request see below) and I try to send the token I got back (like in the documentation). But I always get the following error message "Subscription validation request failed. Response must exactly match validationToken query parameter."
Post request from Azure:
Path: /?validationToken=Validation%3a+Testing+client+application+reachability+for+subscription+Request-Id%3a+3b3f9821-ce3f-23d9-879b-00a23f3
Body: is empty
I tried every part and encoding of the path (like just the request ID or the whole path) but I always get the error message. So whats the right thing to send back?
Firstly, the validation token you receive should be treated as an opaque value and returned unchanged and the error Subscription validation request failed. Response must exactly match validationToken query parameter is trying to tell you that something changed.
Since the validation token comes to you as a URL query parameter, make sure you're working with a properly decoded value in your code before returning it.
Here is the relevant documentation from Microsoft Docs: Notification endpoint validation
POST https://{notificationUrl}?validationToken={opaqueTokenCreatedByMicrosoftGraph}
Other requirements(from the same reference):
response within 10 seconds
200 (OK) status code.
content type must be text/plain.
body must include the validation token.
Code Samples
ASP.NET MVC Sample - Specifically look at the NotificationController.cs file
[HttpPost]
public async Task<ActionResult> Listen()
{
// Validate the new subscription by sending the token back to Microsoft Graph.
// This response is required for each subscription.
if (Request.QueryString["validationToken"] != null)
{
var token = Request.QueryString["validationToken"];
return Content(token, "plain/text");
}
Node.js code sample - Specifically look at listen.js
/* Default listen route */
listenRouter.post('/', (req, res, next) => {
let status;
let clientStatesValid;
// If there's a validationToken parameter in the query string,
// then this is the request that Office 365 sends to check
// that this is a valid endpoint.
// Just send the validationToken back.
if (req.query && req.query.validationToken) {
res.send(req.query.validationToken);
// Send a status of 'Ok'
status = 200;
}
You should return the validationToken from the query string with an HTTP 200 response code. You also have to do that within a few seconds, or the graph will fail the request and your call to create the subscription will fail.
Here is an example of the validation endpoint in ASP.NET Web API 2:
public ActionResult<string> Post([FromQuery]string validationToken = null)
{
if(!string.IsNullOrEmpty(validationToken))
{
Console.WriteLine($"Token: '{validationToken}'");
return Ok(validationToken);
}
}

Error accessing Stream REST Api using JWT

I am trying to use JWT token to access a Stream feed but it is returning 404 everytime.
Token header:
{
"alg": "HS256"
}
Token payload:
{
"resource": "feed",
"action": "read"
}
The token was generated using the jjwt library and signed using the secret provided in my account dashboard. I also validated it on jwt.io and it was a valid token
Url
GET: https://api.getstream.io/api/v1.0/feed/notification/666?api-key=...
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJyZXNvdXJjZSI6ImZlZWQiLCJhY3Rpb24iOiJyZWFkIn0.MUZHXQg0UD6jFpCZN5Mn1e7wwys_1qYuVtfBKtHL8QU
Response
{
"exception": "GetStreamAPI404",
"detail": "sorry you've hit a 404"
}
Am I missing something here? Can't figure out what the problem is.
In order to perform correct permission checking, you need to include the feed_id field in your token payload. The value of the field must be the same as the feed that you are trying to read and be in the form of ${feed_group}:${feed_id}.
For instance, the payload for the request in your question (https://api.getstream.io/api/v1.0/feed/notification/666?api-key=) should be:
{
"resource": "feed",
"action": "read",
"feed_id": "notification:666"
}
Note: API URLs must end with a trailing slash (eg. /api/v1.0/feed/notification/666/?api_key=...)
Auth HTTP headers:
Authorization must only contain the JWT token
stream-auth-type must be sent with the value jwt

Resources