Push Notification for IOS not working - ios

We created the certificate .p12 using the Private Key only option. We tried push notification through MAC and its working fine. I used the below code which is not giving any error but iPhone is not getting any notification. In this Helper is my class to write log to file.
public void PushNotificationIOS(string message, string registrationKey, int type)
{
string deviceID = registrationKey;
int port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["IosPort"]); //2195;
string hostname = System.Configuration.ConfigurationManager.AppSettings["HostName"];//"gateway.sandbox.push.apple.com";
string certPath = string.Empty;
certPath = System.Configuration.ConfigurationManager.AppSettings["CertificatePath"] + System.Configuration.ConfigurationManager.AppSettings["CertificateName"];//"~/Content/PushCertificateNew.p12";
string certificatePath = System.Web.Hosting.HostingEnvironment.MapPath(certPath);
string certPassword = System.Configuration.ConfigurationManager.AppSettings["CertificatePassword"];
TcpClient client = new TcpClient(hostname, port);
try
{
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certPassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
}
catch (Exception ex)
{
Helper.WriteLog("sslStream.AuthenticateAsClient : TLS " + ex.Message);
}
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(StringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"" + message + "\",\"badge\":0,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
Helper.WriteLog("PushNotificationIOS catch I :" + ex.Message);
client.Close();
}
catch (Exception e)
{
Helper.WriteLog("PushNotificationIOS catch II :" + e.Message);
client.Close();
}
}
Can anyone tell us how to trace the issue?

I think the problem is in .p12 creation process from KeyChain.
You can select the cert, and open the arrow to also select the private key and export them together as a .p12 file from Keychain Access.
From that you can generate .pem file using below command in terminal
cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts
You can refer to this for details info

Related

Why does this script cause problems only on Jenkins?

I had to add a job in a multibranch pipeline.
The goal was to automatically install a plugin in jira.
The code runs perfectly fine because I tested it in a Unit Test.
But when I put it as a scripted pipeline on Jenkins, it does not do what it should do.
The goal is to install the plugin on jira, but when I run it on Jenkins it will not be installed.
Also I do not get any json Response, which I get in my JUnit Test.
I really do not know what is different on Jenkins. I already found it weird that I have to approve every single method in my script. Did someone have a similar issue on jenkins before.
I really appreciate your help.
#Test
public void test_install_plugin() throws IOException {
String jsonBody = "{\"pluginUri\": \"http://myServer/job/element/job/mybranch\", \"pluginName\": \"myPlugin\"}";
String token = "-6485649001990379871";
String jiraPath="myServer/rest/plugins/1.0/";
String query = "token="+token;
String url = jiraPath+"?"+query;
URL jiraURL = new URL(url);
HttpURLConnection jiraURLConnection = (HttpURLConnection)jiraURL.openConnection();
jiraURLConnection.setDoOutput(true);
jiraURLConnection.setDoInput(true);
jiraURLConnection.setRequestProperty ("Content-Length",String.valueOf(jsonBody.length()));
jiraURLConnection.setRequestProperty ("Accept", "application/json");
jiraURLConnection.setRequestProperty ("Content-Type", "application/vnd.atl.plugins.install.uri+json");
jiraURLConnection.setRequestProperty ("Authorization", "Basic YWRXXXXXXtaW4=");
jiraURLConnection.setRequestMethod("POST");
OutputStream os = null;
try {
os = jiraURLConnection.getOutputStream();
byte[] input = jsonBody.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
}
catch(IOException ex)
{
System.out.println("Exception: " + ex.getMessage());
}
finally
{
os.close();
System.out.println("responseCode of install request: " + jiraURLConnection.getResponseCode());
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(jiraURLConnection.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response: " + response.toString());
}
catch(IOException ex)
{
System.out.println("Exception: " + ex.getMessage());
}
finally
{
br.close();
jiraURLConnection.disconnect();
}
}

Getting javax.net.ssl.SSLHandshakeException in android 7.0 nougat

I am getting an error
javax.net.ssl.SSLHandshakeException: Connection closed by peer
when i am trying to access a HTTPS url.
my code is:
private void executeHTTRequestVerifyingLogin(String userid, String pwd, String key) throws Exception {
String strReturn = "";
BufferedReader in = null;
HttpClient hc = CUtils.getNewHttpClient();
HttpPost hp = new HttpPost(CGlobalVariables.VERIFYING_LOGIN);
try {
hp.setEntity(new UrlEncodedFormEntity(getNameValuePairs_Login(userid, pwd, key), HTTP.UTF_8));
HttpResponse response = hc.execute(hp);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String data = "";
while ((data = in.readLine()) != null)
sb.append(data);
in.close();
setVerifyingLoginValue(sb.toString());
} catch (Exception e) {
throw e;
}
}
My code is working upto api level 23. I don't know why this exception is thrown in Nougat(Android 7.0) only.

Issue in IOS Push Notification - Authentication failed because the remote party has closed the transport stream

I am using the below code for push notification.
public void PushNotificationIOS(string message, string registrationKey)
{
string deviceID = registrationKey;
int port = 2195;
String hostname = System.Configuration.ConfigurationManager.AppSettings["HostName"];//"gateway.sandbox.push.apple.com";
string certPath = string.Empty;
certPath = System.Configuration.ConfigurationManager.AppSettings["CertificatePath"] + System.Configuration.ConfigurationManager.AppSettings["Cer
String certificatePath = System.Web.HttpContext.Current.Server.MapPath(certPath);
string certPassword = System.Configuration.ConfigurationManager.AppSettings["CertificatePassword"];
TcpClient client = new TcpClient(hostname, port);
try
{
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certPassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(StringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"" + message + "\",\"badge\":0,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
}
I am getting the following error
Authentication failed because the remote party has closed the transport stream.
On Trace, I am getting the below
System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck)
at System.Net.Security.SslState.get_SecureStream()
at System.Net.Security.SslStream.Write(Byte[] buffer)
I tried all the things mentioned in various post but am not able to solve the issue.
Make sure certificate is valid & is not corrupted. You can regenerate certificate to be dead sure.
Try providing all the options for SecurityProtocolType like :
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls, false);
SecurityProtocolType.Tls12 can negotiate Transport layer security 1.1 or downwards too but try all options to be sure.
For more details on SecurityProtocolType refer :
https://msdn.microsoft.com/en-us/library/system.net.securityprotocoltype(v=vs.110).aspx

Unable to generate Access token for flipkart API

I am trying to get New access token for Oauth 2.0 with client credential. I am always getting Forbidden or unauthorized error. While I can directly login to url https://api.flipkart.net/oauth-service/oauth/token?grant_type=client_credentials&scope=Seller_Api and generate the token but going with below code I am not able to generate token
public static String getAccessToken(OAuth2Details oauthDetails) {
URL url;
HttpURLConnection con;
String accessToken = null;
try {
url = new URL("https://api.flipkart.net/oauth-service/oauth/token\?grant_type\=client_credentials\&scope=Seller_Api");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
String clientId = oauthDetails.getClientId();
String clientSecret = oauthDetails.getClientSecret();
String scope = oauthDetails.getScope();
System.out
.println("Authorization server expects Basic authentication");
con.setRequestProperty(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(oauthDetails.getClientId(),
oauthDetails.getClientSecret()));
System.out.println("Retry with client credentials");
int code = con.getResponseCode();
System.out.print(con.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
if (code == 401 || code == 403) {
String s;
while ((s = br.readLine()) != null) {
System.out.print(br.readLine());
}
con.disconnect();
System.out
.println("Could not authenticate using client credentials.");
throw new RuntimeException(
"Could not retrieve access token for client: "
+ oauthDetails.getClientId());
}
}
Map<String, String> map = handleResponse(con);
accessToken = map.get(OAuthConstants.ACCESS_TOKEN);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accessToken;
}
public static String getBasicAuthorizationHeader(String username,
String password) {
System.out.println("uu" + OAuthConstants.BASIC + " "
+ encodeCredentials(username, password));
return OAuthConstants.BASIC + " "
+ encodeCredentials(username, password);
}
public static String encodeCredentials(String username, String password) {
String cred = username + ":" + password;
return new String(Base64.encodeBase64(cred.getBytes()));
}
Remove the "\" from your url
url = new URL("https://api.flipkart.net/oauth-service/oauth/token?grant_type=client_credentials&scope=Seller_Api");
Also make the app-id and and secretlike this
<app-id>:<app_secret>
example kdfjkfjdsakfjd93842908039489:kdjsfkajidsjf8939034820
oauthDetails.getClientId()+":"+oauthDetails.getClientSecret()

Iphone Push notification in hindi is not received

I am sending push notification for Iphone from an asp.net application Like this-
String msg5 = "{\"aps\":{\"NewsId\":3156,\"NewCat\":\"Agra\",\"Date1\":\"11Apr2015\",\"content-available\":1,\"alert\":\"HelloWorld\",\"sound\":\"default\",\"badge\":2}}";
and it is received by the client side perfectly. But When I place some Hindi Data in place of "HelloWorld" on alert key, Notification is not received by client side. Please Explain me what is the issue. My code to send Notification is -
public static void pushMessage(string deviceID)
{
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
String certificatePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Certificates.p12");
//X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "");//password
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(deviceID.ToUpper()));
String msg4 = "{\"aps\":{\"NewsId\":3156,\"NewCat\":\"Agra\",\"Date1\":\"11Apr2015\",\"content-available\":1,\"alert\":\"मुख्यमंत्री ने जर्मनी के उद्यमियों को राज्य में निवेश के लिए आमंत्रित किया\",\"sound\":\"default\",\"badge\":2}}";
String msg5 = "{\"aps\":{\"NewsId\":3156,\"NewCat\":\"Agra\",\"Date1\":\"11Apr2015\",\"content-available\":1,\"alert\":\"HelloWorld\",\"sound\":\"default\",\"badge\":2}}";
writer.Write((byte)0);
writer.Write((byte)msg5.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg5);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
catch (Exception e)
{
client.Close();
}
But In place of UTF8 I use default encoding Like this
byte[] b1 = Encoding.UTF8.GetBytes(msg5)
Hindi text is received as ?????
Try this code, working fine for me..
Changes done
write b1.length instead of msg5.length(as in hindi length vary from original text).
public static void pushMessage(string deviceID, string text)
{
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
String certificatePath = System.Web.Hosting.HostingEnvironment.MapPath("~/cert.p12");
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(deviceID.ToUpper()));
String msg5 = "{\"aps\":{\"NewsId\":3156, \"alert\":\"" + text + "\",\"content-available\":\"1\"}}";
writer.Write((byte)0);
byte[] b1 = Encoding.UTF8.GetBytes(msg5);
writer.Write((byte)b1.Length);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
catch (Exception e)
{
client.Close();
}
}

Resources