Aws SNS for sending Messages Status 'waitingforActivation' - asp.net

I am using aws sns for sending message, but when i am testing on console application it return waitingforActivation in status.
AWSConfigs.AWSRegion = "me-south-1";
AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(AWSAPIKey, AWSSecretKey);
PublishRequest pubrequest = new PublishRequest();
pubrequest.Message = "AWS API SMS";
pubrequest.PhoneNumber = "mobile number of Receiver";
pubrequest.MessageAttributes.Add("AWS.SNS.SMS.SNSType", new MessageAttributeValue { StringValue = "Transational", DataType = "String" });
var response = snsClient.PublishAsync(pubrequest);*

Related

Unable to send notification from an Expo React Native App using Azure Notification Hub REST API

I am trying to receive notifications in an Expo React Native App.
The notifications will be sent using Azure Notification Hub REST API
I followed the steps below :
Added the Android project in Firebase Console
To get the Server Key I followed - Firebase messaging, where to get Server Key?
Configured the FCM ServerKey in Azure Notification Hub
Added the google-services.json at the root in my React Native App and modified app.json as mentioned in - https://docs.expo.dev/push-notifications/using-fcm/
To register in ANH, we first need the SAS Token - https://learn.microsoft.com/en-us/rest/api/notificationhubs/common-concepts I generated the token with the following code
const Crypto = require('crypto-js');
const resourceURI =
'http://myNotifHubNameSpace.servicebus.windows.net/myNotifHubName ';
const sasKeyName = 'DefaultListenSharedAccessSignature';
const sasKeyValue = 'xxxxxxxxxxxx';
const expiresInMins = 200;
let sasToken;
let location;
let registrationID;
let deviceToken;
function getSASToken(targetUri, sharedKey, ruleId, expiresInMins) {
targetUri = encodeURIComponent(targetUri.toLowerCase()).toLowerCase();
// Set expiration in seconds
var expireOnDate = new Date();
expireOnDate.setMinutes(expireOnDate.getMinutes() + expiresInMins);
var expires =
Date.UTC(
expireOnDate.getUTCFullYear(),
expireOnDate.getUTCMonth(),
expireOnDate.getUTCDate(),
expireOnDate.getUTCHours(),
expireOnDate.getUTCMinutes(),
expireOnDate.getUTCSeconds()
) / 1000;
var tosign = targetUri + '\n' + expires;
// using CryptoJS
//var signature = CryptoJS.HmacSHA256(tosign, sharedKey);
var signature = Crypto.HmacSHA256(tosign, sharedKey);
var base64signature = signature.toString(Crypto.enc.Base64);
//var base64signature = signature.toString(CryptoJS.enc.Base64);
var base64UriEncoded = encodeURIComponent(base64signature);
// construct autorization string
var token =
'SharedAccessSignature sr=' +
targetUri +
'&sig=' +
base64UriEncoded +
'&se=' +
expires +
'&skn=' +
ruleId;
console.log('signature:' + token);
return token;
}
I then called the create registration API - https://learn.microsoft.com/en-us/rest/api/notificationhubs/create-registration-id
The registrationID has to be extracted from the response header of the API Call
I used the following code to generate the ANH Regsitration ID
async function createRegistrationId() {
const endpoint =
'https://xxxxxx.servicebus.windows.net/xxxxxxx/registrationIDs/?api-version=2015-01';
sasToken = getSASToken(resourceURI, sasKeyValue, sasKeyName, expiresInMins);
const headers = {
Authorization: sasToken,
};
const options = {
method: 'POST',
headers: headers,
};
const response = await fetch(endpoint, options);
if (response.status !== 201) {
console.log(
'Unbale to create registration ID. Status Code: ' + response.status
);
}
console.log('Response Object : ', response);
for (var pair of response.headers.entries()) {
//console.log(pair[0] + ': ' + pair[1]);
}
location = response.headers.get('Location');
console.log('Location - ' + location);
console.log('Type - ' + response.type);
registrationID = location.substring(
location.lastIndexOf('registrationIDs/') + 'registrationIDs/'.length,
location.lastIndexOf('?api-version=2015-01')
);
console.log('Regsitration ID - ', registrationID);
return location;
}
Next step was to update this registration ID in ANH with the Native Device Token
I used expo-notifications package and the method getDevicePushTokenAsync() method to get the native device token
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const {
status
} = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = (await Notifications.getDevicePushTokenAsync()).data;
console.log(token);
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
return token;
}
The native device token was in the following format on Android device
c6RI81R7Rn66kWZ0rar3M2:APA91bEcbLXGwEZF-8hu1yGHfXgWBNuxr_4NY_MR8d7HEzeHAJrjoJnjUlneAIiVglCNIGUr11qkP1G4S76bx_H7NItxfQhZa_bgnQjqSlSaY4-oCoarDYWcY-Mz_ulW8rQZFy_SA6_j
I then called the updateRegistrationId API - https://learn.microsoft.com/en-us/rest/api/notificationhubs/create-update-registration
async function updateRegistraitonId() {
//IF you use registrationIDs as in returned location it was giving 401 error
const endpoint =
'https://xxxxx.servicebus.windows.net/xxxxxxx/registrations/' +
registrationID +
'?api-version=2015-01';
const endpoint1 = location;
const headers = {
Authorization: sasToken,
'Content-Type': 'application/atom+xml;type=entry;charset=utf-8',
};
//Remember to create well-formed XML using back-ticks
//else you may get 400 error
//If you use the tags element it was giving an error
const regDATA = `<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<GcmRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<GcmRegistrationId>${deviceToken}</GcmRegistrationId>
</GcmRegistrationDescription>
</content>
</entry>`;
const options = {
method: 'PUT',
headers: headers,
body: regDATA,
};
const response = await fetch(endpoint, options);
if (response.status !== 201) {
console.log(
'Looks like there was a problem. Status Code: ' + response.status
);
console.log('Response Object : ', response);
//return;
}
}
According to API documentation, I should get 201 response, I got 200 response code . I am not sure if this is the issue
After this I had the notification handling code to recieve the notification,similar to the code in - https://docs.expo.dev/versions/latest/sdk/notifications/
I then tried to send notification using Test Send from ANH, it failed with the error -
**
"The Token obtained from the Token Provider is wrong"
**
I checked in ANH Metrics, the error was categorized as GCM Authentication error, GCM Result:Mismatch SenderId
I tried to check for documentation to add the SenderId , but I couldnt find anyway to inlcude the SenderId also in the payload of updateRegistration call (in xml atom entry)
I tried to use the device token and send directly from Firebase Console, I did not receive it either.
I used the Direct Send API of Azure notification Hub but still did not receive anything
I am suspecting there could be some issue in the way I am handling notifiations in the client device, I can fix that later , but first I will have to resolve the error I am getting in Test Send in Azure NH
Any help to be able to successfully send using Test Send in ANH or pointers ahead for next steps will be much appreciated

asp.net core OAuth access_token verification fails with "IDX10609: Decryption failed. No Keys tried: token: 'System.String'.:"

I have a single page application in Blazor WASM that connects to OAuth0 and receives JWT token when a user get authenticated via OAuth.
My OAuth application uses symmetric signing with HS256.
I am trying to authenticate the returned tokens using the "Client Secret" from my OAuth app but whereas the id_token gets verified, the access_token always fails with the error:
"IDX10609: Decryption failed. No Keys tried: token: 'System.String'.:"
To perform the verification I use the method found here.
My code looks like that:
var mySecret = "####";
var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
var tokenHandler = new JwtSecurityTokenHandler();
try
{
IConfigurationManager<OpenIdConnectConfiguration> configurationManager =
new ConfigurationManager<OpenIdConnectConfiguration>(
$"{my_oauth_app_domain}.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
var keys = openIdConfig.SigningKeys;
tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateActor = false,
ValidateLifetime = false,
ValidateTokenReplay = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = mySecurityKey,
IssuerSigningKeys = openIdConfig.SigningKeys,
}, out SecurityToken validatedToken);
}
catch(Exception ex)
{
Console.WriteLine($"{ex.Message}: {ex.StackTrace}");
return false;
}
return true;
What I find strange is that the access_token appears to be malformed. I know that it doesn't have to follow the JWT specs but puting it in jwt.io causes an error and fields like "kid" which I have seen in other tokens on the web, are missing.
Here is the token:
eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9nYW50b25vcG91bG9zLmV1LmF1dGgwLmNvbS8ifQ..MQnqWWfe3mBCVeKQ.y8e77jf3VwJNRSoDWjB3v05WrT9IJPL_kdqhxlQFnfMOAyqQJOD1ttl1muYlCJJVwAskaAeBr4FgkcwjiL1s4eS9gcWK7yq-2PPbLkDzXtBjA4kgMGdGyMURl-F2jYBNwxbCuXyBKcxJVwzE4-aluYCAOZ8QaXzqKgmQJdpxIdBluVux7nK49uhvEJ5Pv7ueh7eGcm9AAmHm__TYKPPcpPutHNiuD6J8xoptHFLPjKakECE6ZXgD-xLNp4BHwe_DmW6UDPuZ_OD9G8D-hwayz8l--zZdICEnFywUzSWXFiVPUvn4DszDhzWbJsBNf3dnl2cnKel3EYsB.NvsUTcP9v_iicpQ5AkaC4w
Am I doing something wrong?
I found the problem here. In my request to OAuth0 I did not add the "audience" parameter. This led to an opaque token being issued.

Under the hood of Send function in masstranssit

I'm trying to send command to rabbitMQ by masstransit while i know difference between send and publish , defined a direct exchange but use Send to transit that message after that i'm getting error that "Exchange name" received fanout but current is direct .
Does Send makes exchange to fanout type?
config.ReceiveEndpoint("test-consumer", consumer =>
{
consumer.Lazy = true;
consumer.Consumer<TestConsumer>();
consumer.Durable = true;
consumer.ConfigureConsumeTopology = false;
consumer.Bind("MyExchange", ex =>
{
ex.ExchangeType = ExchangeType.Direct;
ex.RoutingKey = "reza";
});
//binding type from test-consumer exchange to test-consumer queue
// consumer.ExchangeType = "direct";
});
var endPoint = await bus.GetSendEndpoint(new Uri("exchange:MyExchange"));
var send3 = rezEndPoint.Send(new Test { Messaged = "sent from myExchange" },h=> { h.SetRoutingKey("reze"); } );
Since you are specifying the exchange type as direct in the consumer, you need to also set that via the send endpoint:
var endPoint = await bus.GetSendEndpoint(new Uri("exchange:MyExchange?type=direct"));

Adding Conversion events to a cloud message using Firebase Admin SDK

I am able to send Push notifications using the code below but I am also required to associate "Conversion events" with the notification. This can be done through the console but I couldn't find how to do it with SDK.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "test1", "6165" },
{ "test2", "161" },
},
Notification =
{
Body = "",
Title = ""
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
Task<string> response = FirebaseMessaging.DefaultInstance.SendAsync(message, true);
// Response is a message ID string.
response.Wait();
Console.WriteLine("Successfully sent message: " + response);

Amazon Sage Maker: How to authenticate AWS SageMaker End-Point Request

I have an aws sagemaker end-point which need to be called from .Net core client, I have used the AWS SDK that deals with SageMaker and provided the required credentials however, always it keeps saying :
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
var requestBody = "{'url':'"+"https://cdn.pixabay.com/photo/2018/05/28/22/11/message-in-a-bottle-3437294_960_720.jpg" + "'}";
var request = new Amazon.SageMakerRuntime.Model.InvokeEndpointRequest()
{
EndpointName = "CG-model-v1-endpoint",
ContentType = "application/json;utf-8",
Body = new MemoryStream(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(requestBody)))
};
var awsClient = new AmazonSageMakerRuntimeClient(awsAccessKeyId: "XXXX", awsSecretAccessKey: "XXX", region: RegionEndpoint.EUCentral1);
try
{
var resposnse = await awsClient.InvokeEndpointAsync(request);
}
catch (Exception ex)
{
return ApiResponse<bool>.Create(false);
}
I found the error , it was simply because of the request content-type,it had to be application/json instead of application/json;utf-8

Resources