Does anyone know if the crossdomain policy file at salesforce.com has changed? - apache-flex

Suddenly my Flex Apps can no longer connect to salesforce.com via its API, I am getting a security sandbox violation. Login credentials are correct, I have tried them via a different means, and I have obfuscated them below.
This was working fine earlier today and I have not been coding since then.
Anyone else come across this or know what's going on?
Here is the exception returned to my app
Method name is: login
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer connected.
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer sending message 'B89E5879-D7F7-E91E-2082-BBEE231054DD'
'direct_http_channel' channel sending message:
(mx.messaging.messages::HTTPRequestMessage)#0
body = "<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/"><se:Header xmlns:sfns="urn:partner.soap.sforce.com"/><se:Body><login xmlns="urn:partner.soap.sforce.com" xmlns:ns1="sobject.partner.soap.sforce.com"><username>simon.palmer#***.com</username><password>***</password></login></se:Body></se:Envelope>"
clientId = (null)
contentType = "text/xml; charset=UTF-8"
destination = "DefaultHTTPS"
headers = (Object)#1
httpHeaders = (Object)#2
Accept = "text/xml"
SOAPAction = """"
X-Salesforce-No-500-SC = "true"
messageId = "B89E5879-D7F7-E91E-2082-BBEE231054DD"
method = "POST"
recordHeaders = false
timestamp = 0
timeToLive = 0
url = "https://www.salesforce.com/services/Soap/u/11.0"
Method name is: login
*** Security Sandbox Violation ***
Connection to https://www.salesforce.com/services/Soap/u/11.0 halted - not permitted from https://localhost/pm_server/pm/pm-debug.swf
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer acknowledge of 'B89E5879-D7F7-E91E-2082-BBEE231054DD'.
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer fault for 'B89E5879-D7F7-E91E-2082-BBEE231054DD'.
Comunication Error : Channel.Security.Error : Security error accessing url : Destination: DefaultHTTPS
Error: Request for resource at https://www.salesforce.com/services/Soap/u/11.0 by requestor from https://localhost/pm_server/pm/pm-debug.swf is denied due to lack of policy file permissions.

You have to make sure to load the policy from the /services tree, the default policy at the root won't help you. You need to load this policy https://www.salesforce.com/services/crossdomain.xml

The solution to this problem was to set the server protocol and url as follows:
apex = new Connection();
apex.serverUrl = "https://na3.salesforce.com/services/Soap/u/14.0";
apex.protocol = "https";
However, this seems to create a secondary issue of users being locked out, so the issue of non-connectivity remains.
Update: salesforce.com have acknowledged a bug. See my other related post.

Did you recently upgrade to flash player 10? Flash player 10 changes the way policy files work to some degree, and the crossdomain.xml file needs to be updated to address this. In short, Salesforce.com probably isn't prepared for users upgrading to Flash Player 10 yet.

I resolve this issue accessing to the Flash Player Configuration Panel(I just recommend it in a development environment), in the "Global Security" tab, select Always Allow.
Regards.

I am uploading a file from flex to Google docs. Everything is working in the local file however, when we upload the SWF file as S-controls in Salesforce (sandbox), an error appears upon connecting to Google. Please see error below:
Error:[FaultEvent fault=[RPC Fault faultString="Security error accessing url"
faultCode="Channel.Security.Error" faultDetail="Destination: DefaultHTTPS"]
messageId="1F812836-1318-B845-AC01-F51AB1D11518" type="fault" bubbles=false
cancelable=true eventPhase=2]
We tried the following solutions below but nothing seems to work:
FLEX:
- Add the crossdomain.xml in the bin-debug folder: below is the content of the cross domain policy.
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" secure="false" />
<allow-http-request-headers-from domain="*" headers="*" secure="false" />
</cross-domain-policy>
Used flash.system.security.allowinsecuredomain/allowdomain(“*”) in the initialization.
Also tried in the connection.protocol set to http
Salesforce:
Disabled the protocol security in the remote site settings
o Setup -> Administration Setup -> Security Controls -> Remote Site Settings
 URL: http://www.google.com.ph
There’s no problem in connection to Salesforce but upon initialization of the uploading page the security error will appear specifically in the onErrorFault function. Below are code snippets:
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="534" height="462" verticalScrollPolicy="off" horizontalScrollPolicy="off"
creationComplete="init()" showCloseButton="true" close="{this.closeWindow(event)}" roundedBottomCorners="true">
<mx:Script>
<![CDATA[
private function init():void{
Security.allowInsecureDomain("*");
//<salesforce:Connection id="apex" sendRequest="sendRequestListener(event)" serverUrl="http://www.salesforce.com/services/Soap/u/10.0" protocol="http"/>
RESTProxyTest();
send_data();
arrAddedFiles = new Array();
this.uploadGrid.dataProvider= this.acFiles;
this.title = "Attachment: "+this.selectedTimeSheetDetail.Project.label;
}
public function RESTProxyTest():void
{
_conn = new NetConnection();
_conn.addEventListener(AsyncErrorEvent.ASYNC_ERROR, doAsyncError);
_conn.addEventListener(IOErrorEvent.IO_ERROR, doIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doSecurityError);
_conn.addEventListener(NetStatusEvent.NET_STATUS, doNetStatus);
_conn.objectEncoding = ObjectEncoding.AMF3;
_conn.connect(_url);
_responder = new Responder(onResult, onFault);
}
private function send_data():void {
userRequest.url = getLoginURL();
userRequest.addEventListener(ResultEvent.RESULT, httpResult);
userRequest.addEventListener(FaultEvent.FAULT, onErrorFault);
userRequest.send();
}
private function onErrorFault(obj:FaultEvent):void
{
Alert.show("Error:"+obj.toString());
}
private function httpResult(obj:ResultEvent):void
{
trace(obj.toString());
var result:String = obj.result as String;
var pos:int = result.lastIndexOf("Auth=");
var auth:String = result.substr(pos + 5);
txtAuth.text = StringUtil.trim(auth);
placeCall();
}
protected function placeCall():void
{
trace("placeCall");
var headers:Array = ["Authorization: " + "GoogleLogin auth=" + StringUtil.trim(txtAuth.text)];
var postVars:Array = [];
var uri:String = "http://docs.google.com/feeds/documents/private/full?showfolders=true";
_conn.call("RESTProxy.request", _responder, uri, "get", new Array(), postVars, headers);
}
private function getLoginURL():String
{
var url:String = 'https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&' +
'Email=' + this.session.config.gmail + '&' +
'Passwd=' + this.session.config.password + '&service=writely';
return url;
}
]]>
</mx:Script>
<mx:HTTPService id="userRequest" useProxy="false" method="POST" contentType="application/x-www-form-urlencoded" showBusyCursor="true"/>

Related

413 request entity too large - Web API

I'm running into a 413 issue while trying to send data from my web application (.netfx 4.6.1) to my web api (.net core 3.1). In the code below, I send a list over containing byte data of images along with additional data needed to build a file. The expected output is to return a byte array containing the new file. Unfortunately when sending the request I receive an error: Response status code does not indicate success: 413 (Request Entity Too Large).
The error only seems to occur when the file is large to begin with, which makes sense. The research I've done seems to point to settings in IIS, the main ones being maxAllowedContentLength, maxRequestLength, and uploadReadAheadSize. I've tried increasing these values to ones more suited to this process but nothing seems to work. I've adjusted them for both the web application and the web api, as I was not sure which one was causing the problem.
Where does the problem lie? In the application, the API, or both? Is there an additional setting I'm missing to allow an increased size? Is there an issue with how I'm sending the request? Any help is appreciated.
public static async Task<byte[]> CreatePdfFromImageFilesAsync(List<ImageFile> imageFiles)
{
var list = new List<dynamic>();
foreach (var item in imageFiles)
{
list.Add(new
{
Data = Convert.ToBase64String(item.Bytes),
PageOrder = item.PageOrder,
Rotation = item.Rotation,
Type = "PDF"
});
}
var response = _client.PostAsJsonAsync($"{FileCreatorAPI}/api/files/CreateFileFromMultiple", list).Result;
var result = response.EnsureSuccessStatusCode();
var bytes = await result.Content.ReadAsAsync<byte[]>();
return bytes;
}
Below changes worked for me
// If using Kestrel:
.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
//options.Limits.MaxRequestBodySize = null; --did not worked
options.Limits.MaxRequestBodySize = int.MaxValue;
})
// If using IIS:
.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
//options.MaxRequestBodySize = null;
options.MaxRequestBodySize = int.MaxValue;
});
create web.config file and add following configuration
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
Can you check that attribute https://github.com/aspnet/Announcements/issues/267 ?
Using
[RequestSizeLimit(100_000_000)]
on your controller entry point, or more globally setting it this way:
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
EDIT: article from MS: https://dotnet.microsoft.com/download/dotnet-core
I think the problem is on the server. The server is terminating the request because it exceeds it's configured maximum allowable request size.
Which server are you using?
For Nginx users, the directive which determines what the allowable HTTP request size can be is client_max_body_size, the default maximum allowable request size is 1MB.
The limit in Apache is set via the LimitRequestBody directive and defaults to 0 (meaning unlimited) to 2147483647 (2GB).
Check out this article on how you can fix it if you are using any of those two servers.

accessing Google API in Flex - get security error after deploying.

I am using the Google Geocoding API (JSON URL) to perform some geocoding work. I can get it work in the development box. However, once I deploy the application to IIS, I got a security error and tell me the URL is not be able to reach.
Here is the message.
security error accessing ULR - channel security error.
Here is the source code I use. I am pretty sure the URL is correct since I can get the result by accessing it directly in IE.
//call google url serive
var httpService : HTTPService = new HTTPService( );
var temps:String = itemg["ADDRESS_1"] + "," + itemg["CITY"] + "," + itemg["STATE"];
temps = CSVUtil.str_replace(temps,",",",+");
temps = CSVUtil.str_replace(temps, " ","+");
//var urlstring = "http://maps.googleapis.com/maps/api/geocode/json?address=" + temps + "&sensor=false";
var urlstring:String = googleurl + temps + "&sensor=false";
Alert.show(urlstring);
httpService.url = urlstring;
httpService.addEventListener(ResultEvent.RESULT, resultFunction);
httpService.addEventListener(FaultEvent.FAULT, faultfunction);
httpService.send();
Alert.show("request send out");
Try to add the crossdomain.xml on your web server root folder.
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>

SignalR connection issues

I'm getting some issues with SignalR (1.1.2) trying to create a basic realtime chat setup and after spending about a week on it (including trawling through the SignalR source) I'm sort of at the end of what I can try...
I have (I think) a rather complicated SignalR setup consisting of:
Load balanced servers
Redis message bus
Two sites on each server (ASP.NET Webforms VB.NET desktop site and MVC3 C# mobile site)
Each of the sites includes the hub of itself and the other site, so each page can send messages to each site.
Looking into the Chrome inspector (in this example on the mobile site), the hubs are both loaded, the negotiate step for mobile is successful but the connect attempt fails after 3 seconds with the error:
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
which is of course our custom 500 error page after Microsoft.Owin.Host.SystemWeb has thrown:
The connection id is in the incorrect format.
Once this happens, most of the time this will then get into some sort of weird loop where it will continue to throw hundreds of these errors and send off lots of pings followed by a longPolling connect
The solution works perfectly well in my development environment (single IIS instance) but moving to the load balanced test environment is where I see the errors.
I don't know if there's anything else I can add that may help but I'm happy to add it.
I've added the following to the web.config files on both sites:
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
and
<add name="Access-Control-Allow-Origin" value="*"></add>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
The global.asax files have:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
RedisScaleoutConfiguration redisConfig = new RedisScaleoutConfiguration([redisIP], [port], String.Empty, "Name");
redisConfig.Database = 9;
GlobalHost.DependencyResolver.UseRedis(redisConfig);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
HubConfiguration hubConfig = new HubConfiguration();
hubConfig.EnableCrossDomain = true;
hubConfig.EnableDetailedErrors = true;
RouteTable.Routes.MapHubs(hubConfig);
<snip>
}
The JS code I have is along the lines of:
function setUpSignalR() {
//Set up the connections
webConnection = $.hubConnection(pageInfo.webUrl);
mobConnection = $.hubConnection(pageInfo.mobUrl);
//Get the hubs for web and mobile
webHub = webConnection.createHubProxies().messagingHub;
mobHub = mobConnection.createHubProxies().messagingHub;
//Hook up the call back functions
<snip>
//Now, start it up!
mobConnection.logging = true;
mobConnection.start().done(function() {
mobHub.server.joinConversation(pageInfo.conversationGuid, "mobile").fail(function (error) { console.log('JoinConversation for mobile connection failed. Error: ' + error); });
webConnection.start().done(function() {
webHub.server.joinConversation(pageInfo.conversationGuid, "mobile").fail(function (error) { console.log('JoinConversation for web connection failed. Error: ' + error); });
});
});
}
From the SignalR troubleshooting document:
"The connection ID is in the incorrect format" or "The user identity
cannot change during an active SignalR connection" error
This error may be seen if authentication is being used, and the client
is logged out before the connection is stopped. The solution is to
stop the SignalR connection before logging the client out.

"No active security context" error even with the setTimeout trick?

I have this code that is supposed to pull a thumbnail image from a remote server and return it to be displayed in Flex. Unfortunately my code is throwing "No active security context" errors.
After searching I saw a trick with setTimeout that is supposed to fix this, but it isn't working for me. What am I doing wrong?
Here is the Code in Flex 4.0 (Note: File is a custom class)
public function getThumbnail(file:File, callBack:Function):void
{
// only for image files
if (file.mimeType.indexOf("image") > -1) {
var loader:Loader = new Loader();
// create request
var urlVars:URLVariables = new URLVariables();
urlVars.id = file.id;
var req:URLRequest = new URLRequest(THUMBNAIL_URL);
req.data = urlVars;
setTimeout(
function():void {
loader.load(req);
}, 1);
// set load handler
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,
function(event:Event):void
{
var thumbnail:Image = new Image();
thumbnail.source = event.currentTarget.content;
callBack(thumbnail);
});
}
}
Update I placed this in my application.mxml
Security.allowDomain("*");
Security.allowInsecureDomain("*");
Security.loadPolicyFile("http://localhost:8080/crossdomain.xml");
And I modified the code in my action script file to
public function getThumbnail(file:File, callBack:Function):void
{
// only for image files
if (file.mimeType.indexOf("image") > -1) {
var loader:Loader = new Loader();
// create request
var urlVars:URLVariables = new URLVariables();
urlVars.id = file.id;
var req:URLRequest = new URLRequest(THUMBNAIL_URL);
req.data = urlVars;
var context:LoaderContext = new LoaderContext(true);
loader.load(req);
// set load handler
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,
function(event:Event):void
{
var thumbnail:Image = new Image();
thumbnail.source = event.currentTarget.content;
callBack(thumbnail);
});
}
}
I had to modify my server.xml on my J2EE backend to get the crossdomain.xml to show up at the root.
My crossdomain.xml looks like this:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<!--This domain can accept the SOAPAction header from a SWF file from www.example.com -->
<site-control permitted-cross-domain-policies="all" />
<allow-access-from domain="*" secure="false" />
<allow-http-request-headers-from
domain="*" headers="SOAPAction" />
</cross-domain-policy>
I still get the "No active security context" error in Firefox with the debug version of Flash Player.
If I remember correctly (Security policies are a bit of a quagmire in Flash), The Loader class does not check the CrossDomain policy file when loading images. You can instruct it to do so by passing your own LoaderContext instance to loader.load(), for example:
loader.load(urlRequest, new LoaderContext(true));
I don't think you need to use setTimeout in your code; I've not heard of this practice and I'm not sure what it would achieve (other than delaying the load call by 1 ms :)
It may be as simple as loading the cross domain policy from the website you're pulling thumbnails from.
Security.allowDomain("*");
Security.allowInsecureDomain("*");
Security.loadPolicyFile("http://domain.com/crossdomain.xml");
I can't find the link anymore, but there was a bug with version 10.2 of Flash with debugging. I recently upgraded to version 10.3 with the debugger and I no longer get this error.

How to find out my server's IP address through it's domain name from my flex air application?

I'm working on file transfer application where client sends files to cpp server. At client side I can give the server's domain name but not IP address cuz it may vary. So any one can tell me how can I get my server's IP address through it's domain name. I have to put this logic into air application. Thank you.
You might consider the NativeProcess API as a potential solution to your problem.
Open that page and scroll to the bottom; notice they're calling a Python script. You can call any Terminal/Console app you want through the NativeProcess API, and you can feed the process any number of arguments as a Vector.<string>(). Basically, I'm suggesting you might try calling cmd.exe and passing it ping www.your_unique_server.com. Then, you can then catch the responses coming back through nativeProcess.standardOutput and you're Flex/AIR app will have the resolved IP to work with. Here's a simple AIR app I wrote to do this:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout paddingTop="20" paddingLeft="20"
paddingRight="20" paddingBottom="20"/>
</s:layout>
<s:Label text="Enter a Domain Name:"/>
<s:TextInput id="domainTI" width="100%" text="www.google.com"/>
<s:Spacer height="20"/>
<s:TextArea id="pingsTA" width="100%" height="100%"
text="Provide a domain name and click 'Ping!'"/>
<s:Button label="Ping!" click="initializeAndPing();"/>
<fx:Script>
<![CDATA[
private var nativeProcess:NativeProcess;
// called by the button.
private function initializeAndPing():void
{
if(NativeProcess.isSupported)
{
// make NativeProcess ready for use.
nativeProcess = new NativeProcess();
nativeProcess.addEventListener(
ProgressEvent.STANDARD_OUTPUT_DATA, onPingResult);
nativeProcess.addEventListener(
ProgressEvent.STANDARD_ERROR_DATA, onStdError);
nativeProcess.addEventListener(
IOErrorEvent.STANDARD_INPUT_IO_ERROR, onStdInError);
pingTheHost();
}
}
private function pingTheHost():void
{
pingsTA.text="";
var cmdFile:File = new File("C:\\Windows\\System32\\cmd.exe");
var startInfo:NativeProcessStartupInfo;
startInfo = new NativeProcessStartupInfo();
startInfo.executable = cmdFile;
// The \n special chars are necessary
// for the command to be executed.
var ping:String = "ping " + domainTI.text + "\n" ;
nativeProcess.start(startInfo);
nativeProcess.standardInput.writeUTFBytes(ping);
}
private function onPingResult(e:ProgressEvent):void
{
// you would need to parse the IP from the text string
// captured here to make it available as a variable.
pingsTA.text +=
nativeProcess.standardOutput.readUTFBytes(
nativeProcess.standardOutput.bytesAvailable);
}
private function onStdError(e:ProgressEvent):void
{
trace("StdError: " +
nativeProcess.standardError.readUTFBytes(
nativeProcess.standardError.bytesAvailable));
}
private function onStdInError(e:IOErrorEvent):void
{
trace("StdInError: " + e.toString());
}
]]>
</fx:Script>
</s:WindowedApplication>
To use NativeProcess, such as in the app above, you'll need an AIR v2+ SDK (you can overlay a new AIR SDK if you have a <2 SDK) and you'll also need to enable the extendedDesktop profile in your app-descriptor.xml file:
<!-- uncomment this node and remove all but "extendedDesktop" -->
<supportedProfiles>extendedDesktop</supportedProfiles>
One last thought: I believe NativeProcess API requires your AIR app be installed as a native application (i.e. installed by an .exe file). But as you see in the screenshot, this is easy to accomplish with Flash Builder 4+.
However, if you don't have Flash Builder 4, you can always write a build script for ADT, which ships with the AIR SDK. That post by Rich Tretola does a nice job of encapsulating the basics.
Finally, here's what my little app looks like in use:

Resources