Authentication in ASP.NET HttpHandler - asp.net

I have created a HttpHandler to be used with SWFUpload to upload images to the server. This upload is done in an administration backend so users need to be authenticated to upload images.
Initially I made the whole administration area deny annonymous users but because of the way SWFUpload appears to work it wouldn't work correctly with Forms authentication and would return a 302 status code.
I had thought it would be possible to make the location of my handler public in Web.config and use context.User.Identity.IsAuthenticated in my handler to determine if the user is logged in.
My problem: is that context.User.Identity.IsAuthenticated always seems false in the handler after I have logged in. Does anyone have any thoughts on why this might be?

Yes, you'll need to use IRequiresSessionState:
public class CustomGenericHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
//code
}
All your sessions will then be usable in the generic handler.
Hope this helps!

Which browser are you using when testing?
Your solution should work in IE but will fail in FireFox since SwfUpload is Flash based and Flash always send IE cookies to the server since you are logging in (and thereby creating a ASP.NET session cookie) in Firefox but SwfUpload send a different set of cookies.

My problem was specific to some code added to Global.asax to fix SWFUpload cookie bug for non-IE browsers. I had modified the value of the session_cookie_name variable in the Application_BeginRequest event handler to be the same name as I had set in Web.config.
Doing this breaks the functionality across all browsers. The variable value should be left set to its default "ASP.NET_SESSIONID".

Related

ASP MVC - Bunch of random characters in POST request route string

I am trying to log in to my own application, and i have discovered something strange. When I am sending a POST request to a login controller, it somehow redirects itself to a GET login controller, and displays login form with an action set to http://localhost:5898/(X(1)S(1tgv3m2psb2cxqaw4koiyhyt))/Account/Login. Now what the hell is this (X(1)S(1tgv3m2psb2cxqaw4koiyhyt)) thing? Why is it there, and what does it do? And on top of that, how do i get rid of it? I do not want it in there...
It appears that you have set the session provider in your web.config (or on IIS) to use a Cookieless session state. This is the session identifier for your session.
http://msdn.microsoft.com/en-us/library/aa479314.aspx#cookieless_topic2
To get rid of it, you would need to change your sessionState element in your web.config to cookieless="false"
SessionState Web.Config element information
Those things are seen in asp.net when you disable cookie in your browser or your application settings. that is cookieless asp.net. you can start debugging your app from there.
hope it helps

Asp.net jquery ajax request.cookies cross domain

Due to cross domain issues, I decided to try a new workaround for detecting sessions between 2 of my domains. I assumed this process would work as I wasn't trying to set any cookies, and it works fine in chrome and firefox, but not in IE9.
I have stepped through in debug mode and the aspx page I request has no access to it's own Request.Cookies, whereas it does when I use chrome.
The process is:
On domain1, (an asp.net mvc application) the user logs in. As part of that login process, a cookie is set on that domain. If I then hit a test page on this server, I can see the cookie has been set.
On domain2 (an asp.net webforms app), I make a jQuery.ajax request to that test page on domain1, which is meant to check for the cookie and return an encrypted string.
When stepping through during this request to domain2 when called via ajax I can see the request.cookies collection is not populated. Frustratingly, User.Identity.IsAuthenticated is true, but I can't get access to the cookie I set.
Is this just another example of the whole cross domain security in action? To me it seems even making the ajax call using jsonp and all the other various hheaders etc, isn't going to help in this situation as it appears to be something more than that?
It seems that you're correct in your assumption. JQuery will by default not send cookies if its connected to a domain that is not the same as the domain the page is on.
You can try using the xhrFields from the JQuery API to perform the cross domain call.
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
http://api.jquery.com/jQuery.ajax/
Hope that helps!

PageMethods security

I'm trying to 'AJAX-ify' my site in order to improve the UI experience. In terms of performance, I'm also trying to get rid of the UpdatePanel. I've come across a great article over at Encosia showing a way of posting using PageMethods. My question is, how secure are page methods in a production environment? Being public, can anyone create a JSON script to POST directly to the server, or are there cross-domain checks taking place? My PageMethods would also write the data into the database (after filtering).
I'm using Forms Authentication in my pages and, on page load, it redirects unauthenticated users to the login page. Would the Page Methods on this page also need to check authentication if the user POSTs directly to the method, or is that authentication inherited for the entire page? (Essentially, does the entire page cycle occur even if a user has managed to post only to the PageMethod)?
Thanks
PageMethods are as secure as the handler in which they reside.
FormsAuthentication will protect everything except the Login page.
On an unprotected handler, like login, you should expose only methods that 1) are not sensitive or 2) validate the user.
EDIT: in response to comments and other answers regarding CSRF and XSS please see http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx
You're trying to protect against CSRF attacks.
These attacks can be prevented by requiring an authorization code in the POST parameters, and supplying the auth code in the initial page load. (The auth code should be per-IP address and per-user, and should expire quickly)
For added security, you can make each auth-code only usable once, and have each request return a new auth-code. (However, if any request fails, you'll need to reload the page)
I am working on a project that heavily utilizes ASP.Net WebForms Page Methods which I talk to using Ajax. This is rather very convenient for me than writing all my codes in JavaScript.
However, Securing the page methods became an issue which troubled me. I see that I can access the page methods via Postman and Fiddler hence, enabling hackers to play with your APIs.
My solution was quite simple which I discovered accidentally. Adding a static Cookie request to the page method would return error for any app that is NOT the website.
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static string GetAnything(object dat)
{
HttpCookie myguid = HttpContext.Current.Request.Cookies.Get(Constants.Session.PreventHacking);
var hackguid = myguid.Value ?? ""; //other page method contents
return "anything";
}
A postman request to this method would return :
{
"Message": "There was an error processing the request.",
"StackTrace": "",
"ExceptionType": ""}
While a more detailed error would show if on LocalHost.
I understand there are browser ad-ons that can intercept API calls by sitting just beside the website. I have not tested this. A separate security fix has to be built for this however.
I'll update here once I perform some tests.
Think of Pagemethods like a mini webservie local to the page. The fact is they will have no extra checks and verifications in place except those that are placed on the entire website, and those that you choose to put in.
Using Pagemethods is a smart idea from the point of view of 'Encapsulation', and if you're going to use them it doesn't hurt trying to put in some extra security measures in place.

Check cookies in asp.net

I want to check if a user has cookies enabled.
Most solutions involve:
1. creating a cookie
2. redirect the user to a custom page or the same page.
3. Read the cookie.
The issue I have is in the 2nd step. Should I use a query string while doing a response.redirect so that in the next trip I know the cookie has already been set and that I should try to read it? What if the user hard codes the URL(along with that query string) in the browser, while accessing the website?
Also, if I find that the cookies are enabled and I set a session variable to say that cookies are enabled on this browser, so dont check again in that session. Is that OK?
If session is available, is that a good enough indicator that cookies are enabled?
I want to minimize these double trips to each page for checking cookies.
I would use javascript to make an asynchronous request and check to see if the cookies that were set were handed back in this request.
Never pass a querystring. You already hinted at it above, but what if some trickster figures our the url and decides they want to pass their own querystring?
If the user has cookies set up, you can set the session and check that.
Always check the session.
instead of using this technique which involves multiple steps and pages, and extra waiting time for the enduser, can't you just use the HttpBrowserCapabilities class? This particular class has a Cookies property:
HttpBrowserCapabilities.Cookies Property
Grz, Kris.
As per my knowledge I know Two ways to check whether browser enables/accepting cookies
By using "Request.Browser.Cookies"
By using Javascript/Jquery
Example:
if (Request.Browser.Cookies)
{
Response.Write("Welcome To Hello World Cookies Accepted by the browser");
}
else
{
Response.Write("Good Bye To Hello World. Cookie diabled in your browser. Enable cookies and Try again... Cool..");
}

session lost on redirect

I have a web app that is being hit by facebook. The login page retrieves the keys that I need and sets some session variables. When the server then redirects the user to the next page, the session information is lost. I’m running the IIS engine on vista ultimate at the moment, the app pools don’t matter because I’m using a state service and I’m still losing the session state. I’ve tried both the overloaded method of the response.redirect function and also adding a header to the page to force the redirect and none of this seems to work. Does anyone have any ideas of what I’m missing?
I’ve tried both of these:
Response.Headers.Add("refresh", "3;url=Dashboard.aspx")
And
Response.Redirect("Dashboard.aspx", False)
[EDIT]
So i just did a little experiment and well it turns out that when I hit the url directly from the facebook page I get the problem, but when i copy the url for the IFrame into a new browser window and try it it works fine.
[EDIT]
So I found an article on this and after addin gthe header the problem was solved (for now)
http://support.microsoft.com/kb/323752
Response.AddHeader("P3P: CP", "CAO PSA OUR")
when I hit the url directly from the facebook page I get the problem, but when i copy the url for the IFrame into a new browser window and try it it works fine.
If you're in an iframe, any cookies you set are “third-party cookies”. Third-party cookies may be subject to more stringent conditions than the normal “first-party” cookies you are setting when the user is directly on your site. This can be due to different browser default cookie handling or because the user has deliberately configured it like that. (And for good reason: many third-parties are unpleasant privacy-invading advertisers.)
In particular, in IE6+ with the default settings, you cannot set a third-party cookie unless you write a P3P policy promising that you will be a good boy and not flog your users' data to the nearest identify thief.
(In practice of course P3P is a dead loss, since there's nothing stopping the site owner from just lying. Another worthless complication that provides no actual security. Yay.)
I'd try running Fiddler and see if your session cookie is being sent properly with the response when interacting with your app via Facebook.
The session depends also on cookie support by the client. When you say the app "is being hit by facebook" are you sure that by what ever means they are "hitting" you they are supporting cookies?
Response.Redirect and refresh don't carry session. Server.Transfer() can but loses the ability to transfer to other servers/sites.

Resources