C2DM server side ClientLogin with java problem - android-c2dm

I'm trying to implement the server side of C2DM. I have registered my application with Google via the signup process and received an email confirmation, so my user/pwd should be good. The first step is to retrieve the auth token via the ClientLogin. When I run the code, I get a response code 403 / Forbidden. Anyone have any ideas?
log.info("Obtaining the Google C2DM Client Login token.");
// Make POST request
HttpResponse res = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI("https://www.google.com/accounts/ClientLogin");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE"));
params.add(new BasicNameValuePair("Email", "MY_ACCOUNT#gmail.com"));
params.add(new BasicNameValuePair("Password", "MY_PWD"));
params.add(new BasicNameValuePair("service", "ac2dm"));
params.add(new BasicNameValuePair("source", "MY_APP-V0.1"));
HttpPost post = new HttpPost(uri);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
res = client.execute(post);
} catch (Exception e) {
log.error("Error obtaining the Google C2DM Client Login token.", e);
}
log.debug("response="+res);
if (res != null) {
log.debug("Response status code = "+res.getStatusLine().getStatusCode());
log.debug("Response status = "+res.getStatusLine().getReasonPhrase());
}

My problem was pointed out to me here:
http://blog.boxedice.com/2010/10/07/android-push-notifications-tutorial/
The "Password" parameter name should actually be "Passwd".
Thanks to Dannon for the answer.

Related

Getting error for getting access token "HTTP method POST is not supported by this URL, StatusCode=405"

Getting issues for getting access token by using trigger and apex class. I am using "https://www.googleapis.com/auth/drive" as callback URL and endpoint of HTTP Request. My create folder method is working properly if valid access token is provided but I am not getting access token. But I am getting error "HTTP method POST is not supported by this URL, StatusCode=405"
Below is my code
public class GDriveFolderCreationClass {
private final String clientId ='3MVG98EE59.VIHmz7DO7_********************kb0NbJrDULh.q0CmS3TqSuItCtA6mxyxUaa_STYbpue';
private final String clientSecret = '8E70141F********************6307D13F5B72FD850ABA2C9A05124F3B7B9F';
private final String username = 'test#gmail.com';
public class deserializeResponse{
public String access_token;
}
public String ReturnAccessToken (GDriveFolderCreationClass acount){
deserializeResponse resp1= new deserializeResponse();
String reqbody = 'client_id='+clientId+'&client_secret='+clientSecret+'&username='+username;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://www.googleapis.com/auth/drive');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Accept','application/json');
HttpResponse res = h.send(req);
if(res.getstatusCode() == 200 && res.getbody() != null){
resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
}
return resp1.access_token;
}
#future(Callout=True)
public static void createFolderinDrive(String contentName){
GDriveFolderCreationClass account1 = new GDriveFolderCreationClass();
String accessToken;
accessToken = account1.ReturnAccessToken(account1);
createFolder();
}
//Working function for creating folder in google drive
public static void createFolder() {
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://www.googleapis.com/drive/v3/files');
req.setHeader('Authorization', 'Bearer '+accessToken);
req.setHeader('content-type', 'application/json');
String body = '{"name" : "'+'TestFolder'+'","mimeType" : "application/vnd.google-apps.folder"}';
req.setTimeout(60*1000);
req.setBody(body);
Http http = new Http();
HttpResponse res = http.send(req);
}
}
ConnectedAppSS
I have also used the AUTH provider and used callback URL as redirect URI but that also didn't worked. For that I am getting below error in debug log
error ss
Please help me to get access token for my fixed google account to create folder structure in my google drive. Let me know if you want any other details.
Thanks and regards
Firstly get the refresh token by using code authorization and then you can get access token by using refresh token.
Use "https://accounts.google.com/o/oauth2/token" as a endpoint to get access token again and again by using refresh token.
You are using https://www.googleapis.com/auth/drive as an endpoint to POST your request for a token. This URL does not return any authorization tokens.
See https://developers.google.com/identity/protocols/oauth2#2.-obtain-an-access-token-from-the-google-authorization-server.
The endpoint to get the auth tokens; which is easier to do using client libraries is: https://accounts.google.com/o/oauth2/v2/auth

NTLM Auth with RestSharp

I am attempting to create some tests using RestSharp for a project I am working on.
This project uses Single Sign-on NTLM Authentication.
I am attemping to use a NTLMAuthenticator but my getUser request is always failing. I am not positive what URL to put in for the CredentialCache, the project or the SSO Id Provider.
SharedRequests shared = new SharedRequests();
var credential = new CredentialCache
{
{
new Uri("project or ID Provider URL or something else?"),
"NTLM",
new NetworkCredential("doamin\Username", "Password")
}
};
RestClient client = new RestClient();
client.BaseUrl=new Uri("projectURL");
client.Authenticator = new NtlmAuthenticator(credential);
client.PreAuthenticate = true;
RestRequest request = shared.GetCurrentUser();
IRestResponse response = client.Execute(request);
my response always gets a 500 error which is what is expected when no auth cookies are present.

The request was aborted: Could not create SSL/TLS secure channel. (RestSharp, SSL Client Certificates)

I have following code which is calling an API using basic authentication and SSL client certificate but its throwing exception and giving me following error.
"The request was aborted: Could not create SSL/TLS secure channel."
I tried to find a solution on Google but failed to find any solution. Can anyone help me out on this. Thanks.
// Variables
string basicAuthenticationUserName = "username";
string basicAuthenticationPassword = "password";
string clientCertificateFilePath = "Path-To-Certificate-File";
string clientCertificatePassword = "certificate-password";
string url = "https://" + basicAuthenticationUserName + ":" + basicAuthenticationPassword + "#apiserverurl/apimethod";
// Creating RestSharp Request Object
var request = new RestRequest(Method.POST)
{
RequestFormat = DataFormat.Json,
OnBeforeDeserialization = resp =>
{
resp.ContentType = "application/json";
}
};
// Adding Headers
request.AddHeader("Content-Length", "0");
request.AddHeader("Accept", "application/x-null-message");
// Importing Certificates
var certificates = new X509Certificate();
certificates.Import(clientCertificateFilePath, clientCertificatePassword, X509KeyStorageFlags.PersistKeySet);
// Creating RestSharp Client Object
var client = new RestClient
{
BaseUrl = new Uri(url),
ClientCertificates = new X509CertificateCollection { certificates },
Authenticator = new HttpBasicAuthenticator(managingLou, basicAuthenticationPassword)
};
// Executing Request
var response = client.Execute<T>(request);
I have faced the similar issue. Let me mention the steps here for your help.
After the installation of windows service, I went through the following steps to fix the issue:
Go To Start > Run and type Services.msc
Select your service > Right click and choose Properties
Select the 2nd tab "Log On"
Select the radio button "This account"
Enter the username and password of currently log in user. (Make sure Its the same user who has installed the service)
Apply the changes
Start the service

Onelogin Logging a User In Via API not working

I'm using the onelogin REST api to log a user in: https://developers.onelogin.com/api-docs/1/samples/login-user-via-api.
I have followed all the steps successfully to generate a session token with no issues.
The documentation then says to post the session token to this url: https://admin.us.onelogin.com/session_via_api_token
However, when do the post to that URL with the session token it simply re-directs me to the onelogin Sign On Page.
Here is the c# code for the post. I have a valid session token in variable: session_token:
string url = "https://admin.us.onelogin.com/session_via_api_token";
StringBuilder postData = new StringBuilder();
postData.Append("session_token=" + HttpUtility.UrlEncode(session_token) + "&");
postData.Append("auth_token=" + HttpUtility.UrlEncode(""));
//ETC for all Form Elements
// Now to Send Data.
StreamWriter writer = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.ToString().Length;
try
{
writer = new StreamWriter(request.GetRequestStream());
writer.Write(postData.ToString());
}
finally
{
if (writer != null)
writer.Close();
}
This appears to be server side code so this will never be able to successfully get a session with the end-user's browser.
In order for this flow to work properly, you need to redirect the end-user's browser to the https://admin.us.onelogin.com/session_via_api_token URL with just the auth_token value as a POST parameter.
All the above code will do is allow your back end server to get a session cookie, which doesn't help your end-user establish a session at all.
More details can be found here: https://developers.onelogin.com/api-docs/1/samples/login-user-via-api

Apache Http Client 4.5 Authentication Exception when Integrating to ServiceNow

Am trying to connect to my service-now instance using Apache Client 4.5 via a proxy server. Unfortunately the connection is failing with the below exception.
HTTP/1.1 401 Unauthorized
{"error":{"message":"User Not Authenticated","detail":"Required to provide Auth information"},"status":"failure"}
I can understand that this is because of authentication exception, but i did seem to have provide the credential as shown below.
Code Snippet :
public void getRequestWithProxy() throws ClientProtocolException, IOException
{
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("proxy.xxxx.com", 0000),
new UsernamePasswordCredentials("proxyuser", "proxypassword"));
credsProvider.setCredentials(
new AuthScope("instance.service-now.com", 443),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
try {
HttpHost target = new HttpHost("instance.service-now.com", 443, "https");
HttpHost proxy = new HttpHost("proxy.xxxx.com", 0000);
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet httpget = new HttpGet("/api/now/table/incident");
httpget.setConfig(config);
System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
I assume that i have access to the URL am accessing, because the same URL "https://instance.service-now.com/api/now/table/incident" when tried in browser works fine using SSO (Single Sing On).
Please help me with what am missing.
Thanks in advance for your help in this.
Thank you.
You stated it was a URL. new AuthScope should be a hostname and not a URL.