azure sql server firewall settings - azure-sql-database

How to find my computer's external IP address for azure sql server firewall settings? It is different from the one I get from Ipconfig command(IPv4). I can see a specific IP address on the azure portal but want to know if/how I can see it from my machine?

There is a "AutoDetectClientIP" Management API call that updates an existing Firewall Exception to the caller's IP address.
But you need access to a Management Certificate that is valid for the given subscription, the subscription ID, the name of the SQL Azure Server and the name of the Firewall Exception.
Below how you can use that API.
public static bool SetFirewallRuleAutoDetect(string certFilename, string certPassword, string subscriptionId, string serverName, string ruleName)
{
try
{
string url = string.Format("https://management.database.windows.net:8443/{0}/servers/{1}/firewallrules/{2}?op=AutoDetectClientIP",
subscriptionId,
serverName,
ruleName);
HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
webRequest.ClientCertificates.Add(new X509Certificate2(certFilename, certPassword));
webRequest.Method = "POST";
webRequest.Headers["x-ms-version"] = "1.0";
webRequest.ContentLength = 0;
// call the management api
// there is no information contained in the response, it only needs to work
using (WebResponse response = webRequest.GetResponse())
using (Stream stream = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
Console.WriteLine(sr.ReadToEnd());
}
// the firewall was successfully updated
return true;
}
catch
{
// there was an error and the firewall possibly not updated
return false;
}
}
Above information comes from here.

Related

How to access a file server share from an ASP.NET Core web API application published in IIS within the same domain?

I need access to files that are in a files server in my LAN from my Angular app.
I assume that I need to publish my Angular app in the same network, that is, in my IIS Server inside the same LAN
Now on my local machine, I try to access my shared folder \192.168.100.7\OfertasHistoric" but I donĀ“t know how to do it.
When I try this
[HttpGet("directorio")]
public async Task<ActionResult<string[]>> GetDirectoryContents()
{
string[] files = Directory.GetFiles(#"\\192.168.100.7\ofertashistorico");
return files;
}
I get this error
System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/kintela/Repos/Intranet-WebAPI/Intranet.API/\192.168.100.7\ofertashistorico'
It seems that the path that you give to the GetFiles method only searches from the current directory where the project is located downwards and I don't know how to indicate a different one.
I also do not know how to manage the issue of the credentials necessary to access said resource
Any idea, please?
Thanks
I am using below code and it works for me. Please check it.
Steps:
Navigate to the path like : \\192.168.2.50\ftp
Delete \ftp, the address in folder explorer should be \\192.168.2.50, find the folder you want, right click and map network drive.
You can try it with this address ftp:\\192.168.2.50, it will pop up a window. Input you usename and password, then you can check the files.
Test Result
Sample code
[HttpGet("directorio")]
public IActionResult GetDirectoryContents()
{
string networkPath = #"ftp:\\192.168.2.50";
string userName = #"Administrator";
string password = "Yy16";
#region FtpWebRequest
var networkCredential = new NetworkCredential(userName, password);
var uri = new Uri(networkPath);
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = networkCredential;
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("Access to the path '" + networkPath + "' is denied. Error message: " + ex.Message);
}
#endregion
return Ok();
}

Not getting IP address of Client in Java Spring Web Application

I have a java Spring web application, deployed on an Apache server, in which I wish to capture IP address of client using the following code.
public static String getIpFromRequest(HttpServletRequest request){
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
}
return remoteAddr;
}
By this code I'm getting the same IP address for every client. I have referred all stackoverflow questions, but they suggested same above code. Please suggest possible way.

Google OAuth 2.0 for desktop apps for Windows without Admin privileges

I've heard about Google's plan of modernizing OAuth interactions described here: https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html
Then I was looking at the sample desktop application for Windows found here: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp.
It's pretty simple and it was working, but once I started Visual Studio without elevated privileges (as a non-admin), I experienced that the HttpListener was not able to start because of the following error: "Access Denied".
It turned out that starting an HttpListener at the loopback address (127.0.0.1) is not possible without admin rights. However trying localhost instead of 127.0.0.1 lead to success.
I found that there is a specific command that allows HttpListener to start at the given address (and port):
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user
But it also can be only executed with admin rights, so it's not an option.
Still localhost seems to be the best shot but OAuth 2.0 for Mobile & Desktop Apps states the following regarding this section:
See the redirect_uri parameter definition for more information about the loopback IP address. It is also possible to use localhost in place of the loopback IP, but this may cause issues with client firewalls. Most, but not all, firewalls allow loopback communication.
This is why I'm a bit suspicious to use localhost. So I'm wondering what is the recommended way of Google in this case, as I'm not intending to run our application as administrator just for this reason.
Any ideas?
You can use TcpListener for instance instead of HttpListener. It does not need elevation to listen.
The following is a modified excerpt of this sample:
https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp
// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";
// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);
// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
authorizationEndpoint,
System.Uri.EscapeDataString(redirectURI),
clientID,
state,
code_challenge,
code_challenge_method);
// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);
// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();
// Read response.
var response = ReadString(client);
// Brings this app back to the foreground.
this.Activate();
// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
client.Dispose();
listener.Stop();
Console.WriteLine("HTTP server stopped.");
});
// TODO: Check the response here to get the authorization code and verify the code challenge
The read and write methods being:
private string ReadString(TcpClient client)
{
var readBuffer = new byte[client.ReceiveBufferSize];
string fullServerReply = null;
using (var inStream = new MemoryStream())
{
var stream = client.GetStream();
while (stream.DataAvailable)
{
var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
if (numberOfBytesRead <= 0)
break;
inStream.Write(readBuffer, 0, numberOfBytesRead);
}
fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
}
return fullServerReply;
}
private Task WriteStringAsync(TcpClient client, string str)
{
return Task.Run(() =>
{
using (var writer = new StreamWriter(client.GetStream(), Encoding.UTF8))
{
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/html; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + str.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(str);
}
});
}
By default there is a URL pattern http://+:80/Temporary_Listen_Addresses/ which is allowed for all users (\Everyone)
You can use this as a prefix for your listener. More generally (to avoid collisions with other listeners) you should generate a URL under Temporary_Listen_Addresses (e.g. using a GUID) and use that as your listener prefix.
Unfortunately, a sysadmin can use netsh http to delete this entry or to restrict its usage to only certain users. Also, this does not appear to support listening for an HTTPS request as there is no corresponding ACL entry for port 443.
An admin can list all these permitted URL patterns using netsh http show urlacl as a command.

A request to send or receive data was disallowed because the socket is not connected

I am trying to connect to a remote external server using TCP sockets in WCF code
My WCF service is the client which has code using sockets to connect to an external server.
This code sends a request to an external server and receives the server response
int byteCount = 0;
Socket m_socClient;
try
{
string query = "My Request String";
m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse("127:0:0:0");
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, 1234);
EVCommon.Log("COnnecting to" + IPSelected + Port);
m_socClient.Connect(remoteEndPoint);
try
{
if (m_socClient.Connected)
{
EVCommon.Log("Connected to" + IPSelected + Port);
var reQuestToSend = string.Format("POST /ZZZZZ HTTP/1.1\r\nContent-Length:{0}\r\n\r\n{1}", query.Length, query);
byte[] bytesToSend = Encoding.ASCII.GetBytes(reQuestToSend);
byteCount = m_socClient.Send(bytesToSend, SocketFlags.None);
byte[] bytesReceived = new byte[1024];
byteCount = m_socClient.Receive(bytesReceived, SocketFlags.None);
Response271 = Encoding.ASCII.GetString(bytesReceived);
m_socClient.Disconnect(false);
m_socClient.Close(5000);
}
}
catch(Exception ex)
{
EVCommon.Log(ex.Message);
}
}
If I make a windows application with the same client code to connect to the remote server, it is successful. I am able to connect, send and receive
This error occurs only when I bring WCF into the picture. The code fails at if(m_socket.Connected). So it is not able to connect successfully.
A request to send or receive data was disallowed because the socket
is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
Thank you
The difference is that the windows applications runs in the identity of the logged in user and the WCF service runs in the identity of the application pool.
What is probably happening is that the application pool is running as NETWORK SERVICE which does not have the right to open a port.
Try changing the identity of the app pool to your user to check if this is the problem.

HttpWebResponse displays siteminder login even though URLs are configured to be by passed in Siteminder

I am stumped on this problem and have come humbled to the experts on advice for my problem.
I have an ASP.NET MVC app that is Siteminder enabled. In addition, this app has a section of URLS that are web services which provide data to another application. Those URLS have been configured for "bypass" Siteminder authentication in the Siteminder setup. I've double checked the bypass to make sure the Siteminder configuration is correct. I can enter those URLs in a browser and the JSON data is displayed "without" Siteminder authentication. However....
The problem is when I use HttpWebResponse, Stream and StreamReader to retrieve the JSON data when siteminder is enabled, I get the Siteminder "login page HTML" as the string when StreamReader.ReadToEnd() is evoked instead of the JSON formatted data???
This is baffling because I another developer here can access the same web service and get the "correct" JSON formatted data in a PYTHON app. Also, I put it in a regular ASP.NET app so it's not an MVC issue. I get the same result.
Is there another class or library I should use? Is there a configuration setting I need to pass to the web service call? Any help would be greatly appreciated.
Here is the code of one of the web service calls.
public static string GetData()
{
string host = (string)System.Configuration.ConfigurationManager.AppSettings["WEBSERVICE_GET"];
string URL = host + "Api/GetData";
var end = string.Empty;
try
{
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
}
responseStream.Close();
response.Close();
}
}
catch (Exception ex)
{
EmailNotification.SendErrorEmail("Could not get Data from WEBSERVICE + ex);
}
return end;
}