Error: Server did not accept user credentials - pop3

Pop3Client pop3Client;
if (Session["Pop3Client"] == null)
{
pop3Client = new Pop3Client();
pop3Client.Connect("pop.gmail.com", 995, true);
pop3Client.Authenticate("myusername","mypwd",AuthenticationMethod.UsernameAndPassword);
Session["Pop3Client"] = pop3Client;
}
Error : Server did not accept user credentials

Related

How can I use TLS with Paho MQTT over Javascript?

The code I use currently on my website
var client = null;
var device_is_on = null;
var hostname = "********";
var port = "8003";
var clientId = "mqtt_js_" + parseInt(Math.random() * 100000, 10);
var device_topic = "stat/Device_001/POWER";
var status_topic = "cmnd/Device_001/power";
function connect(){
client = new Paho.MQTT.Client(hostname, Number(port), clientId);
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
useSSL: true,
userName : "***",
password : "********",
onSuccess: onConnect,
onFailure: onFail
};
client.connect(options);
}
function onConnect(context) {
options = {qos:0}
client.subscribe(device_topic, options);
client.subscribe(status_topic, options);
var payloadd = "6";
message = new Paho.MQTT.Message(payloadd);
message.destinationName = status_topic;
message.retained = true;
client.send(message);
}
function onFail(context) {
}
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
window.alert("Connection Lost!\nPlease Refresh.");
}
}
function onMessageArrived(message) {
if (message.destinationName == device_topic){
var temperature_heading = document.getElementById("device_display");
temperature_heading.innerHTML = "Air Conditioner: " + message.payloadString;
if (message.payloadString == "ON" || message.payloadString == "o"){
device_is_on = true;
} else {
device_is_on = false;
}
}
}
function device_toggle(){
if (device_is_on){
var payload = "off";
device_is_on = false;
} else {
var payload = "on";
device_is_on = true;
}
message = new Paho.MQTT.Message(payload);
message.destinationName = status_topic;
message.retained = true;
client.send(message);
}
What should I put under the "" var options "" section? currently I am getting the error ERR_CERT_AUTHORITY_INVALID in the console of Google Chrome.
Note 1: This code functions perfectly over http but I am converting to https.
Note 2: I use Mosquitto as my MQTT broker.
Help in much appreciated.
It looks like you are using a self signed certificate. This will not be trusted by your browser so it will not connect, raising the error you have shown.
You have 2 options:
Import the certificate into your browser and mark it as trusted (how you do this will vary depending on what browser you are using). This is only really useful for testing/development because normal users should not be importing random certificates as this opens them up to all kinds of security problems.
Get a real trusted certificate for your website and broker. The simplest/cheapest way to do this will be to use letsencrypt. You can then configure mosquitto to use this certificate.
TLS javascript paho client is available: Github paho.mqtt.javascript/issues/88

PHPMailer verify peer SSL

Full code below. If i change verify_peer to true it will return SMTP ERROR: Failed to connect to server: (0).
But SSL have been installed already. You can check it here
How to solve this? i dont want to skip verifying peer.
Server nginx. (CLOUDFLARE SSL)
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.mail.ru";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "somemail#mail.ru"; // SMTP account username example
$mail->Password = "somepass"; // SMTP account password example
$mail->SetFrom("somemail#mail.ru");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("somemail2#mail.ru");
$mail->SMTPOptions = array (
'ssl' => array (
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
The solution is change the autosigned SSL Certificate to support SNI. You would have to ask to your hosting provider about that.
Regards

QuickBlox create user issue (bad request) without any error message

I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}

azure active directory graph REST api call through SP.WebRequestInfo on SharePoint Online

Trying to make a REST call through SharePoint's SP.WebRequestInfo.
I'm getting the error "The remote server returned the following error while establishing a connection - 'Unauthorized'." trying to call https://graph.windows.net/[Client]/users?api-version=2013-11-0.
I've successfully retrieved a access token.
Can you help me out why i'm getting this error?
Here is the code i'm using:
var url = "https://graph.windows.net/xxx/users/?api-version=2013-11-08";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("GET");
request.set_headers({
"Authorization": token.token_type + " " + token.access_token,
"Content-Type": "application/json"
});
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var responseBody = JSON.parse(response.get_body());
deferred.resolve(responseBody);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
The code for retrieving the token is:
this.getToken = function (clientId, clientSecret) {
var deferred = $q.defer();
var resource = "https://graph.windows.net";
var formData = "grant_type=client_credentials&resource=" + encodeURIComponent(resource) + "&client_id=" + encodeURIComponent(clientId) + "&client_secret=" + encodeURIComponent(clientSecret);
var url = "https://login.windows.net/xxxxxx.onmicrosoft.com/oauth2/token?api-version=1.0";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("POST");
request.set_body(formData);
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var token = JSON.parse(response.get_body());
deferred.resolve(token);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
function errorHandler() {
deferred.reject(response.get_body());
}
return deferred.promise;
};
Erik, something is strange here - you are using the client credential flow from a JavaScript client - this reveals the secret issued to the client app to the user of the JS app.
The client credential flow also requires the directory admin to grant directory read permission to the client application - not sure if this was already configured - nevertheless it must only be used with a confidential client, not a public client like a JS app.
Azure AD does not yet implement the implicit_grant oauth flow using which a JS client app can acquire an access token on behalf of the user over redirect binding (in the fragment). This is a hugh-pro requirement that we're working on - stay tuned.

huawei api sms documentation

any one have the huawei SMS API documentation? (api/sms/sms-list)
I need to know how to talk with this API to get the SMS list:
It must be something like this:
<request>
<PageIndex>1</PageIndex>
<ReadCount>20</ReadCount>
<BoxType>1</BoxType>
<SortType>0</SortType>
<Ascending>0</Ascending>
<UnreadPreferred>0</UnreadPreferred>
</request>
But I got only a error code 100003 as answer. And I don't what that mean.
Thank You,
michel
I have done this on an Huawei E5221 with Python. The error you are getting is because you are not authenticated and need to login first. Then the list can be retrieved.
Also note that all API requests are POST's and not GET's.
Method to login:
def LoginToSMSGateway(sms_gateway_ip, username, password):
api_url = '/api/user/login'
post_data = '<request><Username>'+username+'</Username><Password>'+ base64.b64encode(password) +'</Password>'
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data)
if r.status_code == 200:
result = False
root = ET.fromstring(r.text)
for results in root.iter('response'):
if results.text == 'OK':
result = True
return result
else:
return False
Method to retrieve SMS List (The method will turn the XML results into a Python list of SMS's):
def GetSMSList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
api_url = '/api/sms/sms-list'
post_data = '<?xml version="1.0" encoding="UTF-8"?><request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = {'Referer': 'http://' + sms_gateway_ip + '/html/smsinbox.html'}
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages:
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
return resultsList
To use it(The IP and credentials are the default values and need to be secured.) :
if LoginToSMSGateway('192.168.1.1', 'admin', 'admin'):
print 'Logged in.'
smsList = GetSMSList('192.168.1.1')
for sms in smsList:
print sms.Message
Since this the subject has been posted I think the API has changed a bit.
To get the SMS list, no need to login but you do need to get a sessionID and the corresponding Token. You can use that Method to get them.
def GetTokenAndSessionID(sms_gateway_ip):
url = '/html/smsinbox.html'
r = requests.get(sms_gateway_ip + url)
Setcookie = r.headers.get('set-cookie')
sessionID = Setcookie.split(';')[0]
token = re.findall(r'"([^"]*)"', r.text)[2]
return token, sessionID
And then the Method to get the sms list (It's using the first Method to wrap the sessionID and the Token in the headers).
def GetSmsList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
url = '/api/sms/sms-list'
token,sessionID = GetTokenAndSessionID(sms_gateway_ip)
post_data = '<request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>2</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'__RequestVerificationToken': token,
'Cookie': sessionID
}
r = requests.post(sms_gateway_ip + url, data = post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages :
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
To use it you just need to call it with the ip of the sms gateway: 192.168.8.1
GetSmsList(sms_gateway_ip)
Similar Code in Java hereunder using Apache HTTP Client classes
CloseableHttpClient httpclient = HttpClients.createDefault();
// 1. Have apache HTTPClient manage the cookie containing the SessionID
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// 2. Extract the token
String token = "";
HttpGet hget = new HttpGet("http://192.168.8.1/html/smsinbox.html");
CloseableHttpResponse getRespo = httpclient.execute(hget, httpContext);
try {
StatusLine statusLine = getRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = getRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Get response contains no content");
}
long len = entity.getContentLength();
StringTokenizer st = null;
if (len != -1 && len > 250) {
st = new StringTokenizer(EntityUtils.toString(entity).substring(0, 250), "\"");
}
int i = 1;
while (st != null && st.hasMoreTokens()) {
if (i++ == 10) {
token = st.nextToken();
break;
} else {
st.nextToken();
}
}
} finally {
getRespo.close();
}
System.out.println("Token: " + token);
// 3. Get the SMS messages using the Token
HttpPost hpost = new HttpPost("http://192.168.8.1/api/sms/sms-list");
String xmlRequest = "<request><PageIndex>1</PageIndex><ReadCount>1</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>1</UnreadPreferred></request>";
StringEntity reqEntity = new StringEntity(xmlRequest);
reqEntity.setContentType("text/xml");
hpost.setEntity(reqEntity);
hpost.addHeader("__RequestVerificationToken", token);
CloseableHttpResponse postRespo = httpclient.execute(hpost, httpContext);
try {
StatusLine statusLine = postRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = postRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
System.out.println(EntityUtils.toString(entity));
//Your further processing here.
} finally {
postRespo.close();
}