AWS IoT Core connection over wss on flutter webapp - amazon-web-services

I made a flutter web application, it works perfectly with my local broker over ws, the problem starts when I need to connect the application with AWS, I followed the instructions in this video How to connect to AWS IOT with MQTT with AWS Signature Version 4 authentication?
to authenticate but I can't get it to work.
Could you guide me on this, thank you.
part of my code:
Future initMqtt() async {
_client = MqttBrowserClient(host!, '')
..port = port!
..logging(on: true)
..keepAlivePeriod = 20
..onConnected = onConnected
..onDisconnected = onDisconnected
..onSubscribed = onSubscribed
..websocketProtocols = MqttClientConstants.protocolsSingleDefault
..setProtocolV311();
final mqttMsg = MqttConnectMessage()
.withWillTopic('willtopic')
.withWillMessage('Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
_client.connectionMessage = mqttMsg;
return await connectionMqtt();
}

Related

Authenticating with AWS .NET SDK for Amazon Chime

I'm trying to create meeting using Chime SDK and I'm passing accessKey and accessKeyId to authenticate. However, the request fails with error, 'Invalid session token'. When I pass session token generated using AWS CLI it works fine. I want to generate the session token programmatically from within .net. How to achieve this.
AWSCredentials credentials = new Chime.Credentials(awsAccessKeyId, awsSecretAccessKey, token);
RegionEndpoint region = RegionEndpoint.USEast1;
client = new AmazonChimeClient(credentials, RegionEndpoint.USEast1);
CreateMeetingRequest request = new CreateMeetingRequest();
request.MeetingHostId = meetingHostId;
request.ExternalMeetingId = externalMeetingId;
return await client.CreateMeetingAsync(request);
You are not setting the ClientRequestToken
CreateMeetingRequest request = new CreateMeetingRequest();
request.MeetingHostId = meetingHostId;
request.ExternalMeetingId = externalMeetingId;
//needs request.ClientRequestToken = ????
Tim

Mail code works in localhost but not on the URL website afterwards

I made a web application on visual studio 2017 for ASP.NET core. It has a contact option where users send me an email. It works perfectly in localhost as I receive the feedback. When I build/release using Azure DevOps onto azure app services in the portal my website at its URL loses the functionality of the email option. I wrote the email code using MailKit, if you guys have a better option that works let me know! Thank you.
var message = new MimeMessage();
message.From.Add(new MailboxAddress(inputEmail));
message.To.Add(new MailboxAddress("myemail"));
message.Subject = "Message from: " + inputName;
message.Body = new TextPart("plain")
{
Text = inputMessage
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("email", "password");
client.Send(message);
client.Disconnect(true);
};
return RedirectToAction("Index");
mywebsite.azurewebsites.net is currently unable to handle this request.
The problem is that you are using gmail. GMail only allows you to authenticate using SMTP/IMAP/POP3 after you've authenticated via the web from a particular device.

Which do i need Sendgrid or Mailkit - to send emails from azure webjob

Can i use Mailkit to send emails from an azure webjob using an organizational smtp server? Or do i need to use Sendgrid?
Mine is a .net core 1.1 console application which i then hosted as azure webjob.
For some reason, I am not able to get my webjob working with Mailkit using an organizational Smtp server. The job runs successfully, does not log any errors. BUT not able to send mails out..
here is my code that uses mailkit
using (var client = new SmtpClient())
{
try {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
Logger.LogInformation("Ready to connect to smtp server");
client.Connect(Constants.SMTP_HOST, 25, false);
Logger.LogInformation("connected to smtp server");
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
Logger.LogInformation("Ready to send email");
client.Send(message);
}
catch (Exception ex) {
Logger.LogError("An error occurred");
Logger.LogError(ex.StackTrace);
}
finally {
client.Disconnect(true);
}
}
Can i use Mailkit to send emails from an azure webjob using an organizational smtp server?
If you use the organizational smtp server, then should make sure that your email server policy allowed to that.
I test Mailkit in the Azure WebJob with google email. It works correctly on my side. Before that I turn Allow less secure apps: ON for my gmail account
The following is the demo code.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Tom Gmail", "xx#gmail.com"));
message.To.Add(new MailboxAddress("Tom Hotmail", "xxx#hotmail.com"));
message.Subject = "I am a mail subject";
message.Body = new TextPart("plain")
{
Text = "I am a mail body."
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("sunguiguan#gmail.com", "#WSX3edc");
client.Send(message);
client.Disconnect(true);
}
Console.WriteLine("send mail successful");
Console.Read();
Or do i need to use Sendgrid?
On my opinon, SendGrid also is a good choice, we also could use the free price tier on the Azure. I also test it on myside. it also works correctly. We also could get more detail info from azure official document.
var apiKey ="ApiKey";//System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("xxx#hotmail.com", "Send Grid"),
Subject = "Hello World from the SendGrid CSharp SDK!",
PlainTextContent = "Hello, Email!",
HtmlContent = "<strong>Hello, Email!</strong>"
};
msg.AddTo(new EmailAddress("xxxx#gmail.com", "Test User"));
client.SendEmailAsync(msg).Wait();
}

Call AWS API Gateway from coldfusion

I am trying to call a dead simple function in AWS Lambda through AWS API Gateway.
This is the url that I tried to reach :
https://rt5b22m3l4.execute-api.us-east-1.amazonaws.com/dev/hello
I called it in browser and it works fine. However when I use coldfusion 10 :
<cfscript>
httpService = new http(method = "GET", charset = "utf-8", url = "https://rt5b22m3l4.execute-api.us-east-1.amazonaws.com/dev/hello");
httpService.addParam(name="accept-encoding", value="deflate;q=0", type="header");
httpService.addParam(name="te", value="deflate;q=0", type="header");
result = httpService.send().getPrefix();
response = result.fileContent.toString();
writeDump(result);
</cfscript>
It always return me
ErrorDetail I/O Exception: peer not authenticated
Any help would be very appreciated. Thank you.

why NotFound error occur in REST services with windows Phone app?

i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.