How to make sure a POST is requested from specific domain? - c#

Is there any property in HttpRequest that can make sure if the request is a POST request and it is coming from specific domain?
private bool IsRequestedFromDomain(string domain)
{
// Request.Form is from domain ?
return false;
}

Try to use
Request.ServerVariables["HTTP_REFERER"]
Note this header can be faked.
For a list of server variables, please take a look: ASP ServerVariables Collection

HTTP Referer, but it can be modified.
Only way how to be sure is to send some , randomly generated value to form, store it to session, and in IsRequestedFromDomain compare it.

Use:
Request.UrlReferrer, though it isn't reliable as it can be easily faked and may be changed by proxies.

Related

unable to get complete url after # using query string in asp.net c# [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

Retrieve the Original (Client) Url Without the Default Document [duplicate]

I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>

Is it possible to override the UserHostAddress property of the HttpRequest class?

I have a situation where I need to put my application behind a proxy server, this causes all the request's that are coming to my application to have the same set of IP addresses used by the proxy servers. However the Proxy server provides the real IP address of the requestor in a custom header, that I can use through my application so I can know the real IP address of the requestor. This is mainly used for logging and tracking. Is there a way I can have the UserHostAddress property return the value from this custom header? This would save a lot of work, because this property referenced about a few hundred time.
It's not possible to change the behavior of the UserHostAddress property, however what you can do is add an extension method to the Request class (something like GetRealUserHostAddress()) and just do a global replace on UserHostAddress -> GetRealUserHostAddress() to rapidly sort out all the instances of it in your solution.
public static string GetRealUserHostAddress(this HttpRequestBase request)
{
return request.Headers["HeaderName"] ?? request.UserHostAddress;
}
If you are saying that the proxy returns the real ip address of the client making the request, you don't need to use the UserHostAddress to read it; you can simply read the header directly:
string realIP = HttpContext.Request.Headers["actual_header_key"];
No, it's not possible. You can read the custom header and place in the request context and use that later.

C#, getting cookies with different names

I set cookies based on the referral links and they all start with the same letters, lets say "google", but they end with _xxx, _yyy, _zzz or whatever is the reference.
Now, when I try to get the cookies later, I have the problem that I don't want to check for all of the different cookies, I would like to check for all cookies that start with "google" and based on that I will start a script that goes on with processing.
if (Request.Cookies("google"))
{
run other stuff
}
Any idea how I can add StartWith or something to it? I am a newbie, so not really that into C# yet.
Thanks in advance,
Pat
Well.. HttpRequest.Cookies is a collection. So use LINQ:
var qry = from cookieName in Request.Cookies.Keys
where cookieName.StartsWith("google")
select cookieName;
foreach(var item in qry)
{
// get the cookie and deal with it.
var cookie = Request.Cookies[item];
}
Bottom line: you can't get away from iterating over the entire cookie collection. But you can do it easily using LINQ.
You have to check all the cookies if you want to find ones with a certain suffix (Randolpho's answer will work).
It's not a particularly good idea to do it that way. The problem is that the more cookies you create, the more overhead you put on the server and connection. Say you have 10 cookies: google_aaa, google_bbb, etc. Each request will send all 10 cookies to your server (this includes requests for images, css, etc.
You're better off using a single cookie which is some sort of key to all the information stored on your server. Something like this:
var cookie = Cookies["google"];
if(cookie!=null)
{
// cookie.Value is a unique key for this user. Lookup this
// key in your database or other store to find out the
// information about this user.
}
If you prefer, use lambda expression, this way
var cookie = Request.Cookies.AllKeys.FirstOrDefault(s => s.Contains("yourName"));
Hope this help!

Get the exact url the user typed into the browser

I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>

Categories

Resources