I am invoking a Controller method from javascript Ajax call. When I use localhost (fine only for dev) in below code, it invokes the Controller method but if I use IP address (IP is needed when code is hosted in other some other Linux box) in place of localhost, method is not invoked.
This code works as I can see call in the network tab in browser:
var tmpUrl = "https://localhost:<port>/method1?param1=" + value1 + "¶m2="+value2;
$('#serviceBinding').load(tmpUrl);
But when I use IP address in place of localhost, there is no invocation of controller method.
var tmpUrl = "https://xx.xxx.xxx.xx:<port>/method1?param1=" + value1 + "¶m2="+value2;
$('#serviceBinding').load(tmpUrl);
Below is the method in spring Controller.
#GetMapping("/method1")
#CrossOrigin(origins = "*", allowedHeaders = "*")
public String method1(...
I do not see any error related to CORS in the browser but I see below error in the inspect section of browser
GET <full URL> net::ERR_TIMED_OUT
I think you are not able to reach IP address, you don't have a HTTPS certificate for your IP address or you have an incorrect port.
Try to ping your IP address into CLI using ping or tracert commands to check if you can reach that ip address.
Also, are you able to open the full url in your browser?
Related
I have an application implemented with Spring Boot, where I use Spring Security for authentication. I already have "token based" authentication in place, where clients are required to retrieve a token, and then use that token to authenticate in subsequent requests.
I would like to enhance this so that a token could be restricted to a specific hostname, so that is can only be used for requests from that host. This is similar to what the google maps API does with its API keys, where it is possible to restrict them by IP or host name.
Here is the code I have implemented to try to retrieve the request's host name
public String getClientHostName(HttpServletRequest request) {
String hostName = null;
// get the request's IP address
String clientAddress = httpRequest.getRemoteAddr();
String xfHeader = httpRequest.getHeader("X-Forwarded-For");
if (xfHeader != null) {
clientAddress = xfHeader.split(",")[0];
}
// try to resolve the host name from the IP address
try {
InetAddress address = InetAddress.getByName(clientAddress);
hostName = address.getHostName();
} catch (UnknownHostException e) {
logger.error("Failed to get the host name from the request's remote address. ", e);
}
return hostName;
}
I have 2 issues right now:
This code does not always manage to retrieve the hostname. Sometimes it just returns the IP address. I understand this may be down to some IP spoofing check the InetAddress class does.
When testing requests from different hosts, I do not always get the IP address I am expecting. I often get the IP of another host that is forwarding the request (which I thought would be solved by checking "X-Forwarded-For"). This makes me wonder how to even retrieve the IP of the host that is the real originator of the request.
Is there a reliable way to check the host name of the originator of a request?
have you tried getting hostname by String referrer = request.getHeader("referer"); ?
Also, on client side also you can add a snippet to find out the hostname in the headers.
Or you can provide below code to be added on client side and on server you can read the value of domain which will return hostname
<input type="button" value="Register" onClick="call()"/>
<script>
function call(){
var domain=window.location.hostname;
window.open('http://<your-hostname>/register?domain='+domain,'_self');
}
</script>
I am testing Oauth2 with Twitter, according to discussions Twitter only allows 127.0.0.1 (it considers localhost invalid).
I am using Javascript to open a pop-up window and detect the callback to the urlI registered: https://127.0.0.1:8144/Oauth2Callback
However, my JavaScript originates from localhost, and according to sources the two are considered different for the 'same origin' policy.
How can I write a redirect from 127.0.0.1 to localhost ?
I am using Java & also tuckey-url-rewrite, so either would work.
My Controller looks like this:
#RequestMapping("/oauth2callback")
#ResponseBody
public String callback() {
return "oauth2callback";
}
<rule>
<name>Twitter Hack</name>
<condition name="host" operator="equal"> ??? 127.0.0.1 ??? /condition>
<from>(.*)</from>
<to type="redirect"> ??? localhost ???</to>
</rule>
I want:
twitter --(callback)--> 127 --(redirect)--> localhost
check your OS's etc/host file and set the 127.0.0.1 to localhost string. It should be there by default, but sometimes it can be an issue. On windows, this is present under C:\windows\System\drivers\etc\ folder.
Its the name resolution for your OS, so you can actually put an IP to name mapping for resolving issues on your host.
This seems to work:
#RequestMapping("/oauth2callback")
public String callback(HttpServletRequest request) {
/*
* Terrible hack for testing Twitter Oauth on 'localhost'
*/
if (request.getServerName().contains("127.0.0.1")){
int port = request.getServerPort();
String query = (request.getQueryString() == null) ? "" : "?" +request.getQueryString();
String url = "redirect:https://localhost:" + port +"/oauth2callback" + query;
return url;
}
return "account/oauth2callback";
}
account/oauth2callback is a simple jsp with only :
<body>
<p>oauth2callback</p>
</body>
There's probably a better way to do this through tuckey-url-rewrite.
I am writing a Java Rest Web Service and need the caller's IP Address. I thought I saw this in the cookie once but now I don't see it. Is there a consistent place to get this information?
I saw one example of using an "OperationalContext" to get it but that was not in java.
Inject a HttpServletRequest into your Rest Service as such:
import javax.servlet.http.HttpServletRequest;
#GET
#Path("/yourservice")
#Produces("text/xml")
public String activate(#Context HttpServletRequest req,#Context SecurityContext context){
String ipAddressRequestCameFrom = requestContext.getRemoteAddr();
// header name is case insensitive
String xForwardedForIP = req.getHeader("X-Forwarded-For");
// if xForwardedForIP is populated use it, else return ipAddressRequestCameFrom
String ip = xForwardedForIP != null ? xForwardedForIP : ipAddressRequestCameFrom;
System.out.println("IP is "+ip);
// get the host name the client contacted. If the header `Host` is populated the `Host` header is automatically returned.
// An AWS ALB populated the Host header for you.
String hostNameRequestCameFrom = req.getServerName();
System.out.println("Host is "+hostNameRequestCameFrom);
//Also if security is enabled
Principal principal = context.getUserPrincipal();
String userName = principal.getName();
}
As #Hemant Nagpal mentions, you can also check the X-Forwarded-For header to determine the real source if a load balancer inserts this into the request.
According to this answer, the getHeader() call is case insensitive.
You can also get the servername that the client contacted. This is either the DNS name or the value set in the Host header with an OSI layer 7 load balancer can populate.
1. Example: no headers are populated
curl "http://127.0.0.1:8080/"
returns
IP is 127.0.0.1
Host is 127.0.0.1
2. Example: X-Forwarded-For and Host headers are populated
curl --header "X-Forwarded-For: 1.2.3.4" --header "Host: bla.bla.com:8443" "http://127.0.0.1:8080/"
returns
IP is 1.2.3.4
Host is bla.bla.com
I think you can get the IP through the request object.
If I'm not mistaken, request.getRemoteAddr() or so.
You could do something like this:
#WebService
public class YourService {
#Resource
WebServiceContext webServiceContext;
#WebMethod
public String myMethod() {
MessageContext messageContext = webServiceContext.getMessageContext();
HttpServletRequest request = (HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST);
String callerIpAddress = request.getRemoteAddr();
System.out.println("Caller IP = " + callerIpAddress);
}
}
Assuming you are making your "web service" with servlets, the rather simple method call .getRemoteAddr() on the request object will give you the callers IP address.
If your application is running on a webserver that is located behind a reverse proxy or load balancer, then that proxy can be configured to inject the requested IP address in a request header. Different reverse proxies can inject different headers. Consult the documentation for your proxy server. We listed a couple of the most used in our example below but this is by no means a complete list.
When your client uses a (forward) proxy, then it might insert headers to say what the client IP addres is. Or it might not. And the IP address inserded here might be incorrect.
This means that the value you get by calling request.getRemoteAddr() is the IP address of the immediate upstream source of the request.
As we said, there are many headers for different proxies in use, but x-forwareded-for is most likely to be inserted by a proxy.
As a last note, even if you get an IP address either from the header or from request.getRemoteAddr() it is not guarenteed to be the client IP address. e.g.: if your proxy does not include the IP address of the client then you’ll get the IP address of the proxy or load balancer. If your client works on a private network and connect to the internet via a NAT gateway, then the IP address in the HTTP request will be an address of the NAT server. Or even for a hacker it is quite easy to inject a header with a different IP address. So this means that you cannot reliably find out the IP address of the system that the request originated from.
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : IP_HEADER_CANDIDATES) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
I get the Yahoo IP address using InetAddress class in java. The result of yahoo.com IP address is not working while given in URL of web browsers.
InetAddress[] all = InetAddress.getAllByName("www.yahoo.com");
for (int i=0; i<all.length; i++)
{
System.out.println(" address = " + all[i]);
}
It shows result as,
address = www.yahoo.com/67.195.160.76
address = www.yahoo.com/69.147.125.65
When i entered those ip into browser's url(ie., http://67.195.160.76), the browser shows "Requisted URL not found".
What's the problem in that. Is the result produced by the java program wrong?
The IP address is not wrong. However, the web server is told exactly what you type into the URL bar, and it can choose to show you different content based on the hostname that you use. In this case, a Yahoo web server (which is at that address) is choosing not to show you anything when you request the host 67.195.160.76.
This information is passed in the Host HTTP header. This header is the basis of how virtual hosts, or "vhosts", work.
I'm writing a web application, I need to do a audit log for all the actions in the application. For this purpose I need to get the IP Address of the client systems.
I'm using request.getRemoteAddr() to get the remote IP Address. But this has a problem, if the client is behind a proxy this method will give the IP of the proxy system.
When I did some search I found a header attribute called 'X-FORWARDED-FOR' in the HttpRequest object.
Can somebody tell me how exactly this header property works and how can I used this header to get the IP address of the client system.
Thank you
getRemoteIP returns the remote IP address of the user (assuming all HTTP intermediaries are well behaved wrt XFF header).
String getRemoteIP(HttpServletRequest request) {
String xff = request.getHeader("X-Forwarded-For");
if (xff != null) {
return xff.split("[\\s,]+")[0];
}
return request.getRemoteAddr();
}
The client's proxy - typically a firewall or somesuch - will populate the x-forwarded-for header with the ip it receives from its client, which is typically, but is not required to be (in the case of a user going through multiple proxies or firewalls) the ip of the user's machine.
'X-FORWARDED-FOR' is used for identifying the originating/actual IP address of a client connecting to a web server through an HTTP proxy.
You can simply use the value for this attribute to find out the originating client IP, even if it's behind a proxy.