Logging in to facebook using apache HTTP client - facebook

I am trying to write automated tests for a REST API using apache HTTP client, we are using Facebook as an affiliate to log in.
I have used this question as a starting point:
apache HttpClient to access facebook
But it is using lots of deprecated methods.
I have switched all of these out but I am finding that it is not working.
to validate I have written a method to print out the body response and I am viewing that by making it into a HTML document. When I load that page it has the facebook error message of:
Cookies Required
Cookies are not enabled on your browser. Please enable cookies in your browser preferences to continue.
My code:
CookieStore cs = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response= HttpClientBuilder.create().setDefaultCookieStore(cs).build().execute(httpget);
System.out.println("Login form get: " + response.getStatusLine());
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php");
context.setCookieStore(cs);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "******"));
nvps.add(new BasicNameValuePair("pass", "*****"));
nvps.add(new BasicNameValuePair("lsd", "AVptst2v"));
httpost.setHeader("User-Agent", "Mozilla/5.0");
httpost.setHeader("Host", "www.facebook.com");
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpost.setHeader("Cookie", cs.toString());
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Referer", "https://www.facebook.com/login");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = HttpClientBuilder.create().setDefaultCookieStore(cs).build().execute(httpost,context);
System.out.println("Login form post: " + response.getStatusLine());
System.out.println(printBodyOfResponse(response));

To answer my own question, I found that creating a context and passing that through with each request carried the session, I see lots of answers saying that cookie management is automatic, but for me the only solution was to pass the context throughout
BasicHttpContext context = new BasicHttpContext();
HttpGet get = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response= HttpClientBuilder.create().build().execute(get,context);
System.out.println("Login form get: " + response.getStatusLine());
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php?login_attempt=1");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email",PropertiesUtil.loadSiteProperty("FB_email")));
nvps.add(new BasicNameValuePair("pass", PropertiesUtil.loadSiteProperty("FB_password")));
httpost.setHeader("User-Agent", "Mozilla/5.0");
httpost.setHeader("Host", "www.facebook.com");
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Referer", "https://www.facebook.com/login");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = HttpClientBuilder.create().build().execute(httpost,context);

Related

Power automate send email 401 Unauthorized: [no body] - Spring RestTemplate

We defined email workflow in power automate for sending micro soft’s teams meeting invite, and we tried to send using spring-boot RestTemplate.
However, we are getting error saying “401 Unauthorized: [no body]”.
Here is what we tried in sending teams invitation using RestTemplate
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
data.add("SUBJECT", "xxx");
data.add("START_TIME", "xxx");
data.add("END_TIME", "xxx");
data.add("ATTENDEES", "xxx");
data.add("TEXT_BODY", "xxx");
HttpEntity<MultiValueMap> entity = new HttpEntity<>(data, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
While the same workflow is working sending teams meeting using OKHttp with below code snippet,
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "json formatted string content");
Request request = new Request.Builder().url(<<workflow-url>>).method("POST", body).addHeader("Content-Type", "application/json").build();
Response response = client.newCall(request).execute();
There is no authentication/authorization details are provided while sending teams meeting request using OkHttp.
Any clue, where we are going wrong?

How to start an UiPath Process from Salesforce interface

How I can Start an UiPath Process on UiPath Robot from the Salesforce interface?
I know that Salesforce can send REST API commands to other software.
I tried to do exactly the same thing, like you in your movie on YouTube.
Please, can you look on my/Your apex code bellow, and maybe help me. Thanks!!
{
//#future(callout=true)
public static void startProcess(String param1,String param2)
{
Http http = new Http();
HttpRequest rm = new HttpRequest();
rm.setEndpoint('https://account.uipath.com/oauth/token');
rm.setMethod('POST');
rm.setHeader('Content-Type', 'application/json');
rm.setHeader('X-UIPATH-TenantName', 'ioDefault');
//rm.setTimeout(60000);
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeStringField('grant_type','refresh_token');
gen.writeStringField('client_id','8DEv1AMNXczW3y4U15LL3jYf62jK93n5');
gen.writeStringField('refresh_token','2I7ZERqOZHFmzVzyPUE_sdf-l-dGa4086xN8fyrW-xF8-');
gen.writeEndObject();
rm.setBody(gen.getAsString());
HttpResponse rs = http.send(rm);
System.debug(rs.getBody());
Map<String,Object> res = (Map<String,Object>)JSON.deserializeUntyped(rs.getBody());
System.debug(String.valueOf(res.get('access_token')));
HttpRequest rm2 = new HttpRequest();
rm2.setMethod('POST');
rm2.setEndpoint('https://platform.uipath.com/zuhtkqf/ioDefault/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs');
rm2.setHeader('Content-Type', 'application/json');
rm2.setHeader('X-UIPATH-TenantName', 'ioDefault');
rm2.setHeader('Authorization', 'Bearer '+String.valueOf(res.get('access_token')));
//rm2.setTimeout(60000);
JSONGenerator gen2 = JSON.createGenerator(true);
/// start a simple process without parameters
gen2.writeStartObject();
gen2.writeFieldName('startInfo');
gen2.writeStartObject();
gen2.writeStringField('ReleaseKey','6aa09f52-ef47-47aa-ab2e-8e487e7841e5');
gen2.writeStringField('Strategy','All');
gen2.writeEndObject();
gen2.writeEndObject();
/// start a simple process with parameters
/* gen2.writeStartObject();
gen2.writeFieldName('startInfo');
gen2.writeStartObject();
gen2.writeStringField('ReleaseKey','YOUR release KEY for process see the YouTube movie below');
gen2.writeStringField('Strategy','All');
gen2.writeStringField('InputArguments','{\"param1\":\"'+param1+'\",\"param2\":\"'+param2+'\"}');
gen2.writeEndObject();
gen2.writeEndObject();
*/
rm2.setBody(gen2.getAsString());
HttpResponse rs2 = http.send(rm2);
System.debug(rs2.getBody());
}
}

How to access Spring REST API in JHipster with standalone

i need to call de jhipster rest service in a java sheduling standalone.
but i dont know how, I try with HttpClient libraries and use CredentialsProvider to set de username and password
I cant login use this
HttpGet httpget = new HttpGet("http://localhost:8080/#Login");
but when I try to get de rest jason api i get HTTP 401 Unauthorized
I see de Gatlin Test make in scala and its like there are simulating a web-browser.
So I am stacking here, and I will apreciate anybody that can give me some suggest in how to do these.
These is the code
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(DEFAULT_USER,DEFAULT_PASS));
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
String output;
In this call a have de estatus 401
response = client.execute(new HttpGet(URL_PROMOTORES), context);
statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
response.close();
client.close();
Thanks in advance.
I don't think you should use basicAuth because it is for HTTP basic authentication (RFC 2617) which is different from what JHipster uses in your case login/password form encoded and session.

How to call CQ author URL from a standalone code

I am trying to hit URL in cq Author instance from my standalone code. The URL looks like — http://<somehost>:<someport>//libs/dam/gui/content/reports/export.json
Below is the code:
URL url = new URL(newPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15 * 10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
But I got a 401 error, which is expected, as I'm not passing any authentication information — hence Sling says:
getAnonymousResolver: Anonymous access not allowed by configuration - requesting credentials.
How can I get resolve this?
You may use Basic HTTP authentication. Adding it to the HttpURLConnection is little awkward:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});
Consider using Apache HttpClient:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
DefaultHttpClient authorizedClient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = authorizedClient.execute(request);
InputStream stream = response.getEntity().getContent();

Apache Wink Client - Test a REST service using form auth

I am trying to use the Wink RestClient to do functional testing on a Rest service endpoint. I use mocks for unit testing but I'd like to functionally test it as an endpoint consumer.
I understand some will object to me calling it a REST endpoint while using form-based auth but that is the current architecture I have.
The majority of the resources I want to test are protected resources and the application (running on Tomcat6) is protected by form authentication. (as in the below web.xml snippet).
What I've tried so far is to make an initial call to an unprotected resource, to obtain the set-cookie header, that contains JSESSIONID, and use that JSESSIONID in the header ( via Resource.cookie() ) in subsequent requests but that does not yield fruit.
web.xml
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/login.html?failure=true</form-error-page>
</form-login-config>
</login-config>
My Wink RestClient code looks like below. All responses are 200, but two things I notice are that the response from the call to /j_security_check/ does not include the jsessionid cookie, and the call to the protected resource said I had a signin failure. The payload for the call to j_security_check was captured directly from a previous successful browser request intercepted.
ClientConfig config = new ClientConfig();
config.setBypassHostnameVerification(true);
RestClient restClient = new RestClient(config);
Resource unprotectedResource = restClient.resource( BASE_URL + "/");
unprotectedResource.header( "Accept", "*/*" );
ClientResponse clientResponse = unprotectedResource.get();
String response = clientResponse.getEntity(String.class);
// get jSession ID
String jSessionId = clientResponse.getHeaders().get("set-cookie").get(0);
jSessionId = jSessionId.split(";")[0];
System.out.println(jSessionId);
// create a request to login via j_security_check
Resource loginResource = restClient.resource(BASE_URL + "/j_security_check/");
loginResource.accept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
loginResource.header("referer", "http://localhost:8080/contextroot/");
loginResource.cookie( jSessionId );
loginResource.header("Connection", "keep-alive");
loginResource.header("Content-Type", "application/x-www-form-urlencoded");
loginResource.header("Content-Length", "41");
ClientResponse loginResponse = loginResource.post("j_username=*****&j_password=*************");
/* the loginResponse, as this point, does not have the jsessionid cookie, my browser client does */
Resource protectedResource = restClient.resource(BASE_URL + "/protected/test/");
systemResource.accept("application/json");
systemResource.cookie( jSessionId );
ClientResponse systemResponse = systemResource.get();
response = clientResponse.getEntity(String.class);
System.out.println(response);
Any thoughts or experience with using the Wink RestClient to exercise form-auth-protected resources would be greatly appreciated. I suppose I'd entertain other frameworks, I have heard of REST-Assured and others, but since the application uses Wink and the RestClient seems to provide me with what I need, I figured I'd stick with it.
Found the problem, and the solution
j_security_check was responding to my POST request (to authenticate), with a #302/redirect. That was being followed by the wink RestClient, but my JSESSIONID cookie was not being appended to it. That was causing the response (from the redirected URL) to contain a set-cookie header, with a new header. My subsequent calls, into which I inserted the JSESSIONID from the first call, failed, because that cookie was expired. All I needed to do was instruct the RestClient to NOT follow redirects. If the redirect were necessary, I would construct it on my own, containing the appropriate cookie.
Chromium and Firefox carry the cookie from the original request to the redirected request so it's all good.
Here is some code that worked for me, using JUnit4, RestClient from the Apache Wink project (and a Jackson ObjectMapper)
#Test
public void testGenerateZipEntryName() throws JsonGenerationException, JsonMappingException, IOException
{
final ObjectMapper mapper = new ObjectMapper();
final String BASE_URL = "http://localhost:8080/rest";
// Configure the Rest client
ClientConfig config = new ClientConfig();
config.proxyHost("localhost"); // helpful when sniffing traffic
config.proxyPort(50080); // helpful when sniffing traffic
config.followRedirects(false); // This is KEY for form auth
RestClient restClient = new RestClient(config);
// Get an unprotected resource -- to get a JSESSIONID
Resource resource = restClient.resource( BASE_URL + "/");
resource.header( "Accept", "*/*" );
ClientResponse response = resource.get();
// extract the jSession ID, in a brittle and ugly way
String jSessId = response.getHeaders().get("set-cookie").get(0).split(";")[0].split("=")[1];
// Get the login resource *j_security_check*
resource = restClient.resource(BASE_URL + "/j_security_check");
resource.cookie("j_username_tmp=admin; j_password_tmp=; JSESSIONID=" + jSessId);
resource.header("Content-Type", "application/x-www-form-urlencoded");
resource.header("Content-Length", "41");
// Verify that login resource redirects us
response = resource.post("j_username=admin&j_password=***********");
assertTrue( response.getStatusCode() == 302 );
// Grab a public resource
resource = restClient.resource(BASE_URL + "/");
resource.cookie("j_username_tmp=admin; j_password_tmp=; JSESSIONID=" + jSessId);
response = resource.get();
// verify status of response
assertTrue( response.getStatusCode() == 200 );
// Grab a protected resource
resource = restClient.resource(BASE_URL + "/rest/system");
resource.cookie("j_username_tmp=admin; j_password_tmp=; JSESSIONID=" + jSessId);
// Verify resource returned OK
response = resource.contentType("application/json").accept("*/*").get();
assertTrue( response.getStatusCode() == 200 );
// Deserialize body of protected response into domain object for further testing
MyObj myObj = mapper.readValue(response.getEntity(String.class), MyObj.class );
assertTrue( myObj.customerArchived() == false );
}