Consuming JSON using Silverlight throws SecurityException - json

I am trying to consume the JSON service from a Silverlight application on button click. But while reading the JSON service url, it throws the below exception.
System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.<EndGetResponse>b__9(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)
Below is my code:
private void Button_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
string url = "http://www.javascriptkit.com/dhtmltutors/javascriptkit.json";
client.OpenReadAsync(new Uri(url));
}
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader reader = new StreamReader(e.Result);
}
Please help me to fix it
I added clientaccesspolicy.xml in web folder. But when Fiddler is checked it says, "The requested URL /clientaccesspolicy.xml was not found on this server" . But I could access this xml from my url.
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
<domain uri="http://*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

Before allowing a connection to a network resource, the Silverlight runtime will try to download a security policy file from the domain that hosts the network resource. There are two different methods used to download the security policy that depend on whether the connection request was from a WebClient or HTTP class or whether the connection request was from sockets.
If the connection request was from a WebClient or an HTTP class to a cross-domain site, the Silverlight runtime tries to download the security policy file using the HTTP protocol. The Silverlight runtime first tries to download a Silverlight policy file with a name of "clientaccesspolicy.xml" at the root of the requested target domain using the HTTP protocol.
If the "clientaccesspolicy.xml" is either not found (the web request returns a 404 status code), returned with an unexpected mime-type, is not valid XML, or has an invalid root node, then the Silverlight runtime will issue a request for the Flash policy file with a name of "crossdomain.xml" at the root of the requested target domain, using the HTTP protocol.
HTTP redirects for the policy file are not allowed. A redirect for a policy file will result in a SecurityException of access denied.

Related

Require browser to not cache certificates

We have setup a setup a server at localhost:8081 which would be our default website. We have then opened a https port on 8443 which requires a certificate. The first time there is a request to that port Chrome/Edge shows a popup-dialog with available certificates (1 in our case). We then have a program that kicks in which does other authorizations that makes the certificate available so that the browser can send it to the server. However if we try to connect to that port a second time the browser seems to have cached the certificate and sends it to the server without showing the popup-dialog. We are sure to have invalidated all sessions at the server side. It seems the only way to reprompt the certificate is to restart the browser or go incognito. Is there any way to force the browser not to cache the certificates?
I have managed to solve it by doing two things and before that I just want to clarify what we are doing. We have a smart card reader that detects a card. If a card is inserted, chrome shows certificate dialog. After selecting the certificate the smart card reader authenticates the card through a pin dialog and sends the cards certificate to the server. If the card was removed and reinserted it should reprompt the pin dialog but in our case it did not since chrome/edge cached the session.
We are using Spring boot with Apache and doing the following things solved our problem:
At requesthandler using httpResponse.addHeader("Connection","close"):
private void handleSessionUnlockRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
...
...
httpResponse.addHeader("Access-Control-Allow-Credentials",
"true");
httpResponse.addHeader("Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate");
httpResponse.addHeader("Connection","close");
writer.flush();
httpRequest.getSession().invalidate();
}
At HttpConnector by setting hostConfig.setSessionTimeout(1):
private Connector getHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
connector.setScheme("https");
connector.setSecure(true);
...
...
protocol.setSslEnabledProtocols("TLSv1.2");
protocol.setClientAuth("Required");
for(SSLHostConfig hostConfig : connector.findSslHostConfigs()){
hostConfig.setSessionTimeout(1);
}
return connector;
}

How do I get POCO SecureSMTPClientSession class to work, using NetSSL_Win module?

I have built Poco 1.11 and am unable to get secure SMTP connections, or HTTPS connections in general, to work, with the NetSSL_Win module (i.e. using Windows Schannel rather than OpenSSL). There is a sample in the distribution at NetSSL_Win\samples\Mail\src :
SecureSMTPClientSession session(mailhost);
session.login();
session.startTLS(pContext);
if ( !username.empty() )
{
session.login(SMTPClientSession::AUTH_LOGIN, username, password);
}
session.sendMessage(message);
session.close();
When I run it, the second login() call, after the startTLS() call, throws this error:
SSL Exception: Failed to decode data: The specified data could not be decrypted
The server in this case was smtp.gmail.com, on port 587.
I get the same error message for any other HTTPS client code I try to run as well.
Is anyone successfully using Poco 1.11 for HTTPS connections, using Windows Schannel?

Apacha HttpClient configuration

I'm currently using RestTemplate backed by Apache http client 4.5.6 in my web server for making http requests. My HttpClient configuration is as follows:
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(httpConfigurationProperties.getConnection().getMaxTotal());
connectionManager.setDefaultMaxPerRoute(httpConfigurationProperties.getConnection()
return HttpClients.custom()
.setDefaultRequestConfig(RequestConfig
.custom()
.setConnectionRequestTimeout((int) httpConfigurationProperties.getTimeout().getConnectionRequestTimeout().toMillis())
.setConnectTimeout((int) httpConfigurationProperties.getTimeout().getConnectTimeout().toMillis())
.setSocketTimeout((int) httpConfigurationProperties.getTimeout().getReadTimeout().toMillis())
.build())
.setRetryHandler(StandardHttpRequestRetryHandler.INSTANCE)
.setConnectionManager(connectionManager)
.build();
When I make a HTTP GET, once in a while i see this:
I/O exception (java.net.SocketException) caught when processing
request to {s}->: Connection reset
I have read in another post that this is caused by server(that I'm sending request to) closing the connection without informing client. And StandardHttpRequestRetryHandler was able to retry it. But HTTP POST methods are not retried because they are not idempotent operations. But is there a configuration that can avoid this connection reset in first place?
And I have tried using evictExpiredConnections and does not help. Will setting connectionManager.setValidateAfterInactivity(20000) help validating connection before using?
Before using apache http client I used SimpleClientHttpRequestFactory in RestTemplate and I never faced connection reset issues. Any help is appreciated

System.Net.Sockets.SocketException while connecting to WCF Data Service with Store APP

While I try to use DataServiceCollection.loadAsync() to load data from a remote WCF data servcie, I always get an empty collection, like
CloudEDUEntities ctx = new CloudEDUEntities(uri);
DataServiceCollection<COURSE> dsc = new DataServiceCollection<COURSE>();
var query = from p in ctx.COURSEs select p;
dsc.LoadAsync(query);//The count of dsc will always be 0
dsc.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(complete);
Then I checked the status with loadCompleted method and find that there is an error, like:
System.InvalidOperationException: An error occurred while processing this request. ---> System.Data.Services.Http.WebException: Unable to connect to the remote server ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions 10.0.1.39:8080
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Http.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Data.Services.Http.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Client.HttpWebRequestMessage.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Client.ODataRequestMessageWrapper.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Client.WebUtil.GetResponseHelper(ODataRequestMessageWrapper request, DataServiceContext context, IAsyncResult asyncResult, Boolean handleWebException)
at System.Data.Services.Client.WebUtil.EndGetResponse(ODataRequestMessageWrapper request, IAsyncResult asyncResult, DataServiceContext context)
at System.Data.Services.Client.QueryResult.AsyncEndGetResponse(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Data.Services.Client.BaseAsyncResult.EndExecute[T](Object source, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.QueryResult.EndExecuteQuery[TElement](Object source, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceRequest.EndExecute[TElement](Object source, DataServiceContext context, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceQuery`1.EndExecute(IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceCollection`1.<>c__DisplayClass2.<LoadAsync>b__1(IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceCollection`1.EndLoadAsyncOperation(Func`2 endCall, IAsyncResult asyncResult)
I highly suspect that it is a problem caused by the server. But I can still use the browser to view the dataservice with the URL. Therefore, I checked the server side, the 8080 port is open, and I even added a clientaccesspolicy.xml to the root of the server project. the content:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<socket-resource port="8080" protocol="tcp" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
I closed the firewalls, but the client still cannot successfully load data. My Server is on Windows Server 2008 with SQL Server 2012.
The same WCF Dataservices was deployed on a server running on Windows 7, and the client can successfully load data from it.
I do hope anyone can help me figure out the reason. Thx in advance.
BTW, same code runs smoothly in the console project.
According to your description, I think there is no IP contradiction or port occupation because the same code runs smoothly in your console project. You should check the .appxmanifest file of your Windows Store App, and make sure you have checked the Private Network (Clien & Server) in the capibilities tab.
The Private Network (Client & Server) capability provides inbound and outbound access to home and work networks through the firewall. This capability is typically used for games that communicate across the local area network (LAN), and for apps that share data across a variety of local devices.
You can get more information about capibilities here.

SignalR on HTTPS

I am trying to use SignalR client side libraries on HTTPS server. It works fine on normal server but on HTTPS server, it is throwing an exception.
try
{
...
hubConnection = new HubConnection(signalUrl);
proxy = hubConnection.CreateHubProxy("SignalRConnect");
hubConnection.Start().Wait(); // throws an exception at this line
...
}
catch (Exception ex) {
I am getting exception - "The remote certificate is invalid according to the validation procedure."
}
Does anybody has an idea how to configure client side SignalR?
Thank you in advanced.
Medha
If your server requires custom client certificates then you can use SignalR 1.1 beta to add an x509certificate to the connection before the request is made.
Issue is resolved. I removed the code of creating proxy from the controller and add code on client side and get context of the hub from controller code.
var hubContext = GlobalHost.ConnectionManager.GetHubContext();
and use hubContext for client notification.