Calling External WCF Service (using generated client) from CRM sandboxed plugin OnPremise is failing - plugins

How to call HTTPS WCF web service in Plugin, plugin assembly is registered in sandbox mode. I am getting System.Security.SecurityException exception, Can somebody please provide the way to all https web service. My code is below :
BasicHttpBinding myBinding = new BasicHttpBinding();
myBinding.MaxReceivedMessageSize = Int32.MaxValue;
myBinding.Name = “basicHttpBinding”;
if (EndPoint.ToLower().Contains(“https://”))
{
//Throwing exception here – System.Security.SecurityException exception,
ServicePointManager.ServerCertificateValidationCallback += (sendr, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072 | (SecurityProtocolType)192;
myBinding.Security.Mode = BasicHttpSecurityMode.Transport;
}
else
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
myBinding.Security.Mode = BasicHttpSecurityMode.None;
}
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress endPointAddress = new EndpointAddress(EndPoint);
WebIALClient myClient = new WebIALClient(myBinding, endPointAddress)

Since you are in on-premise version, you can register the plugin assembly in non-sandbox mode. ie Isolation mode = none to overcome such errors.
In case you wanted to use sandbox mode, try using WebClient class for invoking WCF service call. Read more
using (WebClient client = new WebClient())
{
byte[] responseBytes = client.DownloadData(webAddress);
string response = Encoding.UTF8.GetString(responseBytes);
tracingService.Trace(response);
// For demonstration purposes, throw an exception so that the response
// is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
}

Can you try and also include: using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Route("api/ConvertUpload/{env}/{id}")]
public string Get(string env, string id)
{
return "hi";
}
You may have to use WebClient as #Arun has mentioned.

Related

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());
}
}

Performing http web request to a server requiring SAML authentication

I have simple app that is trying to do a http web request to a server that requires SAML authentication. Authenticated users will get a http response header with a special token, which is what I need to ultimately get.
My app is .net based and does a pretty simple http web request. It does the request then parses the response header. I later traverse the header for the specific token I need:
...
try
{
WindowsIdentity identity = HttpContext.User.Identity as WindowsIdentity;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UseDefaultCredentials = true;
req.AllowAutoRedirect = true;
req.Timeout = 30000;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (response == null)
{
throw new Exception("No HTTP Response");
}
StringBuilder sb = new StringBuilder();
Byte[] buffer = new byte[8192];
Stream rStream = response.GetResponseStream();
int count = 1;
do
{
count = rStream.Read(buffer, 0, buffer.Length);
if (count != 0)
{
sb.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
} while (count > 0);
...
The problem is that the server I'm requesting requires SAML authentication. It redirects to an ADFS server upon request. My app server currently uses kerberos authentication but I can enable it to do SAML as well. Both servers use the same IdP (ADFS) and are in the same enterprise.
My question is - since my app can also do SAML on the same IdP, is there anyway I could get the necessary claims to connect directly into the destination server?

Authorisation issue while accessing a page from repository in CQ5.

I'm trying to hit a page which contains a xml structure. for that i'm using this code
#Reference
private SlingRepository repository;
adminSession = repository.loginAdministrative( repository.getDefaultWorkspace());
String pageUrl = "http://localhost:4504"+page+".abc.htm";
conn = (HttpURLConnection)new URL(pageUrl).openConnection();
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you'rusing Firefox 3.6.3
urlResponse = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader( new InputStreamReader(urlResponse) );
While accesing the page i'm getting this issue
org.apache.sling.auth.core.impl.SlingAuthenticator getAnonymousResolver: `Anonymous access not allowed by configuration - requesting credentials`
I'm logged in as an admin and whenever i'm directly hitting this urlfrom browser it is working properly bt while accessing it thriugh my code i'm getting this error.
any suggestion ?
If you are trying to call an url on an author instance, the following method I use in one of my projects might help (using apache commons HttpClient):
private InputStream getContent(final String url)
HttpClient httpClient = new HttpClient();
httpClient.getParams().setAuthenticationPreemptive(true);
httpClient.getState().setCredentials(new AuthScope(null, -1, null),
new UsernamePasswordCredentials("admin", "admin"));
try {
GetMethod get = new GetMethod(url);
httpClient.executeMethod(get);
if (get.getStatusCode() == HttpStatus.SC_OK) {
return get.getResponseBodyAsStream();
} else {
LOGGER.error("HTTP Error: ", get.getStatusCode());
}
} catch (HttpException e) {
LOGGER.error("HttpException: ", e);
} catch (IOException e) {
LOGGER.error("IOException: ", e);
}
}
Though at it is using admin:admin it only works on a local dev instance, if you are on a productive environment, I wouldn't put the admin password in plaintext, even though it is onyl code...
You are mixing up sling credentials & http credentials. While you are logged in at the sling-repository the http session is not aware of any authentication informations!

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 Abdera Client giving No credentials available for NTLM <any realm>#proxy.tcs.com:8080

I have seen many forum posts for this and tried several suggestions but still I am not able to solve this. The code works good at my home system, but behind the organization firewall it gives a exception message :
No credentials available for NTLM #proxy.tcs.com:8080
Here is the method which I am using
private static void UseAbdera() throws IOException
{
try
{
Abdera abdera = new Abdera();
AbderaClient client = new AbderaClient(abdera);
client.setProxy("OrgProxyHost", 8080);
NTLMAuthenticatorClass authenticator = new NTLMAuthenticatorClass("username", "password");
Authenticator.setDefault(authenticator);
NTCredentials ntcr = new NTCredentials("username", "password", "greenhouse.lotus.com", "India.TCS.com");
client.addCredentials("https://greenhouse.lotus.com", null, null, ntcr);
ClientResponse resp = client.get("https://greenhouse.lotus.com/forums/atom/service");
org.apache.abdera.model.Document<org.apache.abdera.model.Service> service_doc = resp.getDocument();
service_doc.writeTo(System.out);
System.out.println("\n");
org.apache.abdera.model.Service service = service_doc.getRoot();
org.apache.abdera.model.Collection collection = service.getCollection("Forums Feed Collection", "My Topics");
String coll_uri = collection.getResolvedHref().toASCIIString();
org.apache.abdera.model.Entry entry = abdera.newEntry();
entry.setTitle("TEST REPLY !");
// Mark private
resp = client.post(coll_uri, entry);
switch (resp.getType())
{
case SUCCESS:
String location = resp.getLocation().toASCIIString();
System.out.println("New entry created at: " + location);
break;
default:
System.out.println("Error: " + resp.getStatusText());
}
} catch (URISyntaxException ex)
{
Logger.getLogger(IBMConnectionMessages_ForumPractice.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is the exception log I get
org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: ntlm authentication scheme selected
Jul 6, 2012 10:42:03 AM org.apache.commons.httpclient.HttpMethodDirector processProxyAuthChallenge
INFO: No credentials available for NTLM #orgProxyHost:8080
Exception in thread "main" java.lang.IllegalStateException
at org.apache.abdera.protocol.client.CommonsResponse.(CommonsResponse.java:44)
at org.apache.abdera.protocol.client.AbderaClient.execute(AbderaClient.java:692)
at org.apache.abdera.protocol.client.AbderaClient.get(AbderaClient.java:216)
at org.apache.abdera.protocol.client.AbderaClient.get(AbderaClient.java:404)
at IBMConnectionMessages_ForumPractice.UseAbdera(IBMConnectionMessages_ForumPractice.java:231)
at IBMConnectionMessages_ForumPractice.main(IBMConnectionMessages_ForumPractice.java:45)
Please help, I have spent half a day on it.
your proxy may need ntlm authentication, so provide your proxy authentication details as NTCredentials while setting proxy credentials.