Signalr send message from browser to .net client on the same machine - asp.net

We need to communicate a native application with a web application.
We think to use signalr to send the message/command.
The pipeline would be:
User clicks to make an action.
Javascript (with signalr) send a message to a server in azure.
The server re-send the message a specific client. It must be the client installed on the same machine.
Once the result is completed, NET sends the resulting reverse.
The matter is, How I can find client from the same machine in the signalr Server?
The organization in our system is:
There is center/gym.
Every center has staff who can login.
We could identify client at the same center with some file configuration. Saving our key center, for example. But, in a center, could there are more than one.NET client installed on the different computer.
We think to use the private IP of the computer to make a key on the signalr server.
var ips = [];
var RTCPeerConnection = window.RTCPeerConnection ||
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
var pc = new RTCPeerConnection({
// Don't specify any stun/turn servers, otherwise you will
// also find your public IP addresses.
iceServers: []
});
// Add a media line, this is needed to activate candidate gathering.
pc.createDataChannel('');
// onicecandidate is triggered whenever a candidate has been found.
pc.onicecandidate = function (e) {
if (!e.candidate) { // Candidate gathering completed.
pc.close();
console.log(ips);
return;
}
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
ips.push(ip);
};
pc.createOffer(function (sdp) {
pc.setLocalDescription(sdp);
}, function onerror() { });
This data can be obtained in .NET client without a problem. But in javascript, the previous code works regularly. In some PC, it only returns ipv4. And in Mozilla it doesn't work.
How can we identify both clients? Do You know another way to reach the goal?
Thanks,

Finally, we didn't find a good solution filtering ip adress.
We did the as follow:
We used URI schema to launch our app. URI Schema windows
Public Class RegistrarURI
Const URI_SCHEME As String = "xxx"
Const URI_KEY As String = "URL:xxx"
Private Shared APP_PATH As String = Location.AssemblyDirectory() ' "C:\Program Files (x86)\xxx.exe"
Public Shared Sub RegisterUriScheme()
Using hkcrClass As RegistryKey = Registry.ClassesRoot.CreateSubKey(URI_SCHEME)
hkcrClass.SetValue(Nothing, URI_KEY)
hkcrClass.SetValue("URL Protocol", [String].Empty, RegistryValueKind.[String])
Using defaultIcon As RegistryKey = hkcrClass.CreateSubKey("DefaultIcon")
Dim iconValue As String = [String].Format("""{0}"",0", APP_PATH)
defaultIcon.SetValue(Nothing, iconValue)
End Using
Using shell As RegistryKey = hkcrClass.CreateSubKey("shell")
Using open As RegistryKey = shell.CreateSubKey("open")
Using command As RegistryKey = open.CreateSubKey("command")
Dim cmdValue As String = [String].Format("""{0}"" ""%1""", APP_PATH)
command.SetValue(Nothing, cmdValue)
End Using
End Using
End Using
End Using
End Sub
End Class
In an Azure WebApp we launch a SignalR Server. This server will send data from our .NET app to Chrome.
To achive that, when the web is loaded, we connect to the signalR server. To build de uri, We send the connectionId from Javascript client to the .NET Client.
Then, when the native process is completed. .NET client send the information to signalR server, and this server mirrored the data to javacript client using the connectionId.
To avoid launch some instance of our native app, we use IPC channel to send data to one instance to the previous and closind the new one.
Link to source Blog source

Related

IdentityModel.AspNetCore problem with proxy credentials for backchannel HttpClient

I'm using IdentityModel.AspNetCore to manage client access tokens in a background service. Access to the internet is only possible through a corporate proxy server which uses windows authentication.
The proxy server is configured in Windows options and the background service detects the settings, however authentication doesn't work and I'm constantly getting The proxy tunnel request to proxy 'http://proxy:8080/' failed with status code '407'. How can I configure the HttpClient to use the windows credentials for authentication against the proxy server?
I've already tried the following, but this doesn't work:
services.AddAccessTokenManagement(options =>
{
options.Client.Clients.Add("sapci", new ClientCredentialsTokenRequest
{
Address = hostContext.Configuration["HttpProxy:TokenEndpoint"],
ClientId = hostContext.Configuration["HttpProxy:ClientId"],
ClientSecret = hostContext.Configuration["HttpProxy:ClientSecret"],
GrantType = OidcConstants.GrantTypes.ClientCredentials,
AuthorizationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc2617,
ClientCredentialStyle = ClientCredentialStyle.AuthorizationHeader
});
})
.ConfigureBackchannelHttpClient(client => new HttpClient(new HttpClientHandler()
{
DefaultProxyCredentials = CredentialCache.DefaultCredentials,
}));
I believe you can do this at app startup, to ensure you capture all client usages:
HttpClient.DefaultProxy = new WebProxy()
{
Credentials = CredentialCache.DefaultCredentials
}:
I would reduce your problem to deploying a minimal console app and running it with the same user account etc as your service. Once that works your main app will also.
Sometimes these things are infrastructure related also: eg in the past, with IIS clustered environments, I've had to use a service account and register a service principal name, eg to prevent use of computer accounts. I doubt that is relevant to .Net Core / Kestrel though, which I assume you are using.

BizTalk 2016: How to use HTTP Send adapter with API token

I need to make calls to a rest API service via BizTalk Send adapter. The API simply uses a token in the header for authentication/authorization. I have tested this in a C# console app using httpclient and it works fine:
string apiUrl = "https://api.site.com/endpoint/<method>?";
string dateFormat = "dateFormat = 2017-05-01T00:00:00";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("token", "<token>");
client.DefaultRequestHeaders.Add("Accept", "application/json");
string finalurl = apiUrl + dateFormat;
HttpResponseMessage resp = await client.GetAsync(finalurl);
if (resp.IsSuccessStatusCode)
{
string result = await resp.Content.ReadAsStringAsync();
var rootresult = JsonConvert.DeserializeObject<jobList>(result);
return rootresult;
}
else
{
return null;
}
}
however I want to use BizTalk to make the call and handle the response.
I have tried using the wcf-http adapter, selecting 'Transport' for security (it is an https site so security is required(?)) with no credential type specified and placed the header with the token in the 'messages' tab of the adapter configuration. This fails though with the exception: System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
I have tried googling for this specific scenario and cannot find a solution. I did find this article with suggestions for OAUth handling but I'm surprised that even with BizTalk 2016 I still have to create a custom assembly for something so simple.
Does anyone know how this might be done in the wcf-http send adapter?
Yes, you have to write a custom Endpoint Behaviour and add it to the send port. In fact with the WCF-WebHttp adapter even Basic Auth doesn't work so I'm currently writing an Endpoint Behaviour to address this.
One of the issues with OAuth, is that there isn't one standard that everyone follows, so far I've had to write 2 different OAuth behaviours as they have implemented things differently. One using a secret and time stamp hashed to has to get a token, and the other using Basic Auth to get a token. Also one of them you could get multiple tokens using the same creds, whereas the other would expire the old token straight away.
Another thing I've had to write a custom behaviour for is which version of TLS the end points expects as by default BizTalk 2013 R2 tries TLS 1.0, and then will fail if the web site does not allow it.
You can feedback to Microsoft that you wish to have this feature by voting on Add support for OAuth 2.0 / OpenID Connect authentication
Maybe someone will open source their solution. See Announcement: BizTalk Server embrace open source!
Figured it out. I should have used the 'Certificate' for client credential type.
I just had to:
Add token in the Outbound HTTP Headers box in the Messages tab and select 'Transport' security and 'Certificate' for Transport client credential type.
Downloaded the certificate from the API's website via the browser (manually) and installed it on the local servers certificate store.
I then selected that certificate and thumbprint in the corresponding fields in the adapter via the 'browse' buttons (had to scroll through the available certificates and select the API/website certificate I was trying to connect to).
I discovered this on accident when I had Fiddler running and set the adapter proxy setting to the local Fiddler address (http://localhost:8888). I realized that since Fiddler negotiates the TLS connection/certificate (I enabled tls1.2 in fiddler) to the remote server, messages were able to get through but not directly between the adapter and the remote API server (when Fiddler WASN'T running).

Apple Push Notifications on Windows Server 2008 not working

I'm stuck and I hope somebody here will help me.
For a few days I'm trying to send apple push notifications from windows server 2008. But nothing is send or received. In fact, I've moved everything to simple mvc application so it can be debug easier and I've noticed that it hangs when I try to force sending the push notifications (on push.StopAllServices(true); )
They were working (and still are) from windows server 2012R2 with the same approach to send notifications so I guess the certificates and code are fine.
I'm using windows service & push sharp to send notifications. target framework: 4
The test project is MVC 2.0 target framework 4
I've installed asp.net 4.5 on the server
I've installed certificate via mmc in Personal (the private key is available, granted permission for IUSR and IIS_USRS) and Trusted Root Certificate Authorities.
Port 2195 is open
Here's the code:
private void Initizalize()
{
push = new PushBroker();
//appleCert is path to my .p12 certificate on disk.
var cert = new ApplePushChannelSettings(false, appleCert, "***");
//I've read somewhere that it was helpful to force send notifications. Well, in my case it's not.
var settings = new PushServiceSettings();
settings.AutoScaleChannels = false;
settings.Channels = 3;
settings.MaxAutoScaleChannels = 3;
//Wire up the events for all the services that the broker registers
push.OnNotificationSent += NotificationSent;
push.OnChannelException += ChannelException;
push.OnServiceException += ServiceException;
push.OnNotificationFailed += NotificationFailed;
push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
push.OnChannelCreated += ChannelCreated;
push.OnChannelDestroyed += ChannelDestroyed;
push.RegisterAppleService(cert, settings);
}
public void SendPush()
{
Initizalize();
var token = hard coded token that exists;
var output = "msg";
push.QueueNotification(new AppleNotification()
.ForDeviceToken(token)
.WithAlert(output)
.WithBadge(1)
.WithSound("default"));
push.StopAllServices(true);
}
It raises event "OnNotificationSent", nothing else.
One more thing that may be important. Sending and receiving push notifications was and is working from windows server 2012 but it's windows azure virtual machine so installing the certificate was different.
Any ideas?
Even the information that it cannot be done will be helpful!
edit:
One problem solved:
Apparently you need to have reference to NewtonSoft.Json in order to call StopAllServices. It doesn't hang now but nothing is received by the device.
Looks like on Windows Server 2008 apns certificates private key must have granted permission for user that wants to use it.
As I wrote before I've granted it for IIS_USRS but that's only for applications running under IIS. And since I was using windows service it wasn't working.
So what I did was check user for windows service (Services -> Log On As) and granted permission to certificates private key for this user.

Directory.CreateDirectory failed on Remote Server

I am working on a small project, in asp.net mvc3, that would copy the deployment files from a local drive to a share drive on a window server 2008 R2 server. I am connected using WMI, and the connection is successful. However, I tried to create a folder, and I receive the message "Logon failure: unknown user name or bad password." Here is a sample code:
bool isConnected = false;
options.Username = user.Name.Trim();
options.Password = user.password.Trim();
mScope = new ManagementScope("\\\\xxx.xxx.xxx.xxx\\root\\cimv2", options);
mScope.Connect();
if (mScope.IsConnected == true)
{
//I've gotten to this point. Then, the code below throw the exception
Directory.CreateDirectory(#"\\\\xxx.xxx.xxx.xxx\Tester\shareFile.txt");
isConnected = true;
}
I'd like to know what am I doing? Is that the right way of doing it?
it is the correct way however it will be the current user you are trying to access that gets passed to the remote computer to create the directory. The management scope at this point has nothing to do with Directory.CreateDirectory. These are 2 different "worlds". you do give the creds to ManagementScope but this has no affect on Directory.CreateDirectory. you could use impersonation to do what you are wanting to:
How do you do Impersonation in .NET?
it is unclear though if you are doing this in ASP.NET/MVC or a different platform. your tags indicate ASP.NET MVC but not your main question.
remember, if you are using ASP.NET/MVC, the credentials of the app pool are being used to perform such actions.

Novell eDirectory with .NET DirectoryServices

In our company, we have a project which should use Novell eDirectory with .net applications.
I have tried Novell Api (http://www.novell.com/coolsolutions/feature/11204.html) to connect between .NET applications. It is working fine.
But, as per requirement, we specifically need .net API to connect not with Novell Api, which is not working. Connection and binding with .NET Api DirectoryServices not working.
Our Novell eDirectory is installed with following credentials:
IP address: 10.0.x.xx(witsxxx.companyname.com)
Tree : SXXXX
New Tree Context: WIxxxK01-NDS.OU=STATE.O=ORG
ADMIN Context is: ou=STATE,o=ORG
admin : admin
password: admin
I used Novell Api and used following code
String ldapHost ="10.0.x.xx";
String loginDN = "cn=admin,cn=WIxxxK01-NDS,OU=STATE,o=ORG";
String password = string.Empty;
String searchBase = "o=ORG";
String searchFilter = "(objectclass=*)";
Novell.Directory.Ldap.LdapConnection lc = new Novell.Directory.Ldap.LdapConnection();
try
{
// connect to the server
lc.Connect(ldapHost, LdapPort);
// bind to the server
lc.Bind(LdapVersion, loginDN, password);
}
This is binding correctly and searching can be done.
Now my issue is with when I trying to use .NET APi and to use System.DirectoryServices
or System.DirectoryServices.Protocols, it is not connecting or binding.
I can't even test the following DirectoryEntry.Exists method. It is going to exception.
string myADSPath = "LDAP://10.0.x.xx:636/OU=STATE,O=ORG";
// Determine whether the given path is correct for the DirectoryEntry.
if (DirectoryEntry.Exists(myADSPath))
{
Console.WriteLine("The path {0} is valid",myADSPath);
}
else
{
Console.WriteLine("The path {0} is invalid",myADSPath);
}
It is saying Server is not operational or Local error occurred etc. I don't know what is happening with directory path.
I tried
DirectoryEntry de = new DirectoryEntry("LDAP://10.0.x.xx:636/O=ORG,DC=witsxxx,DC=companyname,DC=com", "cn=admin,cn=WIxxxK01-NDS,o=ORG", "admin");
DirectorySearcher ds = new DirectorySearcher(de, "&(objectClass=user)");
var test = ds.FindAll();
All are going to exceptions.
Could you please help me to solve this? How should be the userDN for DirectoryEntry?
I used System.DirectoryServices.Protocols.LdapConnection too with LdapDirectoryIdentifier and System.Net.NetworkCredential but no result. Only same exceptions.
I appreciate your valuable time and help.
Thanks,
Binu
To diagnose your LDAP connection error, get access to the eDirectory server from the admins, and use iMonitor (serverIP:8028/nds and select Dstrace), in Dstrace clear all tabs and enable LDAP tracing, then do your bind see what happens on the LDAP side to see if there is a more descriptive error there. Or if you even get far enough to bind and make a connection.

Resources