To check for existence of resource in asp.net directory - c#

I need to check weather the requested resource by user in browser is present in my asp.net website directory or not and if it is not present than redirect user to error page.
As I have removed a number of pages from my website and they already got indexed in google bot or sometimes typed by user directly in url.
so whenever request like this made from the browser, my code should do something like following;
if(requested url does not exist)
{
Response.Redirect("error.aspx");
}
how to achieve that programatically.
Thanks.

If i am not wrong this would be the solution you are looking for:
string URL ="mypage.aspx";
if (File.Exists(Server.MapPath(URL)))
{
Response.Redirect(URL,false);
}
else
{
Response.Redirect("~\\404PageNotFound.aspx", true);
}

Related

Getting user of C# aspx project and finding the current user.

I am trying to check if the current user of a web app matches a particular one by doing this:
string t = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
when i console log this string i receive: UserOne
The problem i am running into is this:
if(t.Equals("UserOne"))
{
//this part does not fire off
}
else
{
//this part fires off
}
i don't understand. I'm clearly receiving the value of system.Security.Principal.WindowsIdentity.GetCurrent().Name; and as far as I can tell the if statement logic is correct.
Please help.
If you are running this in a console app, WindowsIdentity.Name will return your user name.
If you are running this in a ASPX site, WindowsIdentity.Name may return something completely different, e.g. the user name associated with the app pool in which your ASPX application is running.
For more information on this, check out this answer.

Authenticate GET requests to files in a folder C# MVC

I have a web site (IIS, C#.Net, MVC4) where users are (forms-)authenticated and they upload media files (mostly .mp4) and authorize set of users to play back on demand. I store these files on local storage.
I play these files using jwplayer back to the authorized users on demand.
jwplayer expects I pass the url directly for it to play, but I didn't want to expose a direct url.
I really have to restrict unauthorized access to these files as they are private files.
I tried implementing a controller method to handle https://mysite/Video/Watch?VideoId=xyz, and return FileStream of the actual file. It works on a browser directly. (Though not sure how efficient it is for large files.)
But the problem is, jwplayer looks for urls of pattern http(s)://domain/path/file.mp4[?parameter1=value1&parameter2=value2 and so on.]
When I give a url like https://mysite/Video/Watch?VideoId=xyz, it says 'No playable sources found' without even sending a HEAD request.
If I expose the urls directly, the files are available for anybody to download, which will break the privacy.
Worst case, I would at least want to avoid hot links which will live for ever.
I have also looked at www.jwplayer.com/blog/securing-your-content/ but did not find the solutions suitable.
My questions are,
Is there a way I can retain the pattern of the url http(s)://domain/path/file.mp4 and still control the access to the file?
If (1.) is not possible, how do I leverage the parameters that could be passed on the url. With the parameters, I can think of signed urls. What should I do on the server if I have to provide and handle/validate signed urls.
Just not to hinder the performance, after any validation, can I somehow get the iis to handle the filestream rather my code?
I implemented an HTTPModule to allow/block access to the file. This addresses my questions 1 & 3.
Code snippet below.
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
//Get the file extension
string fileExt= Path.GetExtension(app.Request.Url.AbsolutePath);
//Check if the extension is mp4
bool requestForMP4 = fileExt.Equals(".mp4", StringComparison.InvariantCultureIgnoreCase);
//If the request is not for an mp4 file, we have nothing to do here
if (!requestForMP4)
return;
//Initially assume no access to media
bool allowAccessToMedia = false;
//....
// Logic to determine access
// If allowed set allowAccessToMedia = true
// otherwise, just return
//....
if(!allowAccessToMedia)
{
//Terminate the request with HTTP StatusCode 403.2 Forbidden: Read Access Forbidden
app.Response.StatusCode = (int)HttpStatusCode.Forbidden;
app.Response.SubStatusCode = 2;
app.CompleteRequest();
}
}

How can I make sure a url provided by the user is not a local path?

I'm writhing a web application (ASP.Net MVC, C#) that require the user to provide urls to RSS or Atom Feed that I then read with the following code :
var xmlRdr = XmlReader.Create(urlProvidedByUserAsString);
var syndicFeed = SyndicationFeed.Load(xmlRdr);
While debugging my application I accidentally passed /something/like/this as an url and I got an exception telling me that C:\something\like\this can't be opened.
It looks like a user could provide a local path and my application would try to read it.
How can I make this code safe? It probably is not sufficient to check for https:// or http:// at the begining of the url, since the user could still enter something like http://localhost/blah. Is there any other way, maybe with the uri class to check if an url is pointing to the web?
Edit: I think I also need to prevent the user from entering adresses that would point to other machines on my network like this example: http://192.168.0.6/ or http://AnotherMachineName/
Try:
new Uri(#"http://stackoverflow.com").IsLoopback
new Uri(#"http://localhost/").IsLoopback
new Uri(#"c:\windows\").IsLoopback

Facebook "fan gate" with C#/asp.net

The problem is that 1) Facebook seems so fluid with how it allows developers to interact with it (FBML, iFrame, different versions of SDKs) and 2) Everything I find is either PHP or Javascript and I have NO experience with those. What I am trying to do seems sooo simple, and I can't believe there isn't an easy way to do this.
What I have:
I used Visual Studio 2010 to create a simple web application (asp.net/C#) that asks the user for some info (first name, last name, email, etc.). I have a button on there called "Submit" that, when clicked, saves the entered data into a database. I have this hosted on GoDaddy (I know, I know...heh) and it works just fine. No problem here.
I created a "Facebook App" that uses the iFrame thingy so that basically I have a new tab on Facebook that displays my web app mentioned above. This works fine too. The tab is there, the web app is there, and users can enter the data and it is saved to the database. No problem here.
What I WANT:
I want the web app (the thing displayed by the facebook app) to only show the data entry part if the user currently "likes" the facebook entity. I DO NOT want to have to ask permission. I just want to know if they are a fan of the company's facebook "page" that has this app. So I need two things here, shown in my pseudo code below:
Part 1 (check if user is already a fan):
If (user is fan)
{
Show data entry area (unhide it)
}
else
{
Show "Click the like button to see more options"
}
Part 2 (listen for "like" event)
WhenLikeButtonPressed()
{
Show data entry area (unhide it)
}
I've seen stuff about "visible to connection", C# sdk, edge.create, etc. but I just can't make heads or tails of it. I don't mind putting in Javascript or PHP if someone could please give me exact, "Fan Gate for Dummies" steps. Please, I'm going crazy over here :-(
The key is is the signed_request that Facebook posts to your app when the user accesses the page. It contains the data on whether or not the user likes the page. You shouldn't need to worry about catching edge events on an actual tab FB page as it get's reloaded when the user likes/unlikes the page.
You'll need to decode the signed request with your app secret to get the like info. There are examples provided for PHP but I'm sure with a little google help you can find decode info for the signed_request for asp.net/c#.
Here's the php decode for reference:
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
and the link https://developers.facebook.com/docs/authentication/signed_request/ the like info will be contained in the page variable

Internet Explorer showing cached page (which requires a cookie to be viewed)

I have a folder in my webserver with some aspx pages that can only be accessed if a certain cookie exists.
On th page_load event i'm checking whether this cookie exists, if not redirect to Default.aspx. This works great with browsers such as Google Chorme and FireFox (3, I have not tested 2 yet). But... for some reason IE will send some sort of cookie still as my website thinks that there is a cookie available of some sorts..
So I added a button to my page to delete the cookie. but the cookie does not exist according to my code (which is correct). My assumption then was that IE caches the page. So after wiping the cache does my page code work properly and you get redirected to Default.aspx.
Is there some sort of way to deny access to the folder if that cookie does not exist, so that IE isn't showing a page that doesn't work?
It's kind of hard to explain.
My cookie checking code is this:
protected void Page_Load(object sender, EventArgs e)
{
{
SimpleAES decrypt = new SimpleAES();
//Check for Authentication Cookie
HttpCookie auth_Cookie = new HttpCookie("WEB_AUTH");
auth_Cookie = Request.Cookies["WEB_AUTH"];
if (auth_Cookie != null)
{
//Some code to execute if Cookie exists and holds correct values
}
else
{
//If there isn't a cookie, redirect to login.aspx
Response.Redirect("~/Default.aspx");
}
}
}
Any help provided would be welcome!
Thanks
ADDED
I just want these pages in folder 'XXX' not be displayed if that cookie is not available. but IE loads the page from it's local cache rather than check whether it can actually load this. What to do?
EDIT
The pages in the folder 'XXX' have 1 master page which is where the Cookie checking code resides in.
You need to prevent browser from caching the page. You should set Response.Cache according to your requirements ( http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache(v=VS.100).aspx).
Note that browser in theory can completely ignore your caching headers and load page from its own cache anyway, in practice all browsers respect caching headers.

Categories

Resources