Will this Cookie Checker reliably detect if user is accepting cookies? - c#

I want my page to set cookies on users in order to track when and if they return, and will be keeping their unique visitor id in a database. I want to avoid creating cookie records for users which do not accept cookies (such as bots and crawlers), so I need a way to check if they are accepting cookies or not. I've devised the following code.
private bool CookiesAreEnabled()
{
bool result = false;
HttpCookie CookieChecker = new HttpCookie("CookieChecker");
CookieChecker.Value = "Do you see me?";
CookieChecker.Expires = DateTime.Now.AddSeconds(10.0d);
Response.Cookies.Set(CookieChecker);
CookieChecker = new HttpCookie("CookieChecker");
CookieChecker = Request.Cookies["CookieChecker"];
if (CookieChecker != null)
{
result = true;
CookieChecker = new HttpCookie("CookieChecker");
CookieChecker.Value = "";
CookieChecker.Expires = DateTime.Now;
Response.Cookies.Set(CookieChecker);
}
return result;
}
It seems to me that this should detect that cookies are disabled, but it doesn't! In my testing so far using Firefox with cookies turned off, the code reports that cookies are enabled! Am I barking up the wrong tree as far as detecting if cookies are enabled? Or am I making a newby-style mistake?

Not sure if overall this code is right, but Response.Cookies.Set(CookieChecker); will set on response that browser is yet to receive and process. when you immediately after call Request.Cookies["CookieChecker"]; this examines current request you're processing - one that browser generated before even receiving Set-Cookie request.
At a minimum you need to let browser process response, then examine the next request to see if the cookie is there.

if you want to use that approch the only way is to use 2 request: the first you set a cookie, the second you read it. You cannot do it with only one request.
Otherwise I think you can achieve it with javascript (this is a pseudo code):
/*first you check if there is already a cookie with the identifier*/
if(document.cookie.indexOf('cookiewithuniqueidentifier') == -1) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
if (cookieEnabled) {
/*ajax request to the server for requesting an unique identifier*/
/*save a cookie with that identifier*/
document.cookie='cookiewithuniqueidentifier=936DA01F-9ABD-4d9d-80C7-02AF85C822A8'
}
}

Related

Losing Cookies and Session Variables during AuthorizeCore

I'm currently working on getting a test environment stood up (it is currently called DEV) and am experiencing some weird issues.
When you first come to the site, we have an agreement page. Hitting the "I Agree" button will force the user through an Action to check to see if they are a member of the site already or not. We do use a demo mode also, but that is not part of the issue.
The issue I'm currently experiencing is the following. Initially in the Action, we create a Cookie called "siteaccept". Once that is created, we determine if the site is in demo mode or not, then move on to getting the user (actual user or demo user). Once the user is found, we log their Id in a Cookie called "cntPOC", and also create a Session variable by the same name with the same data (original developers wrote much of this convoluted logic which I want to change before someone asks why keep a Session and Cookie). We then do a RedirectToAction to the Action to bring up the main page of the site.
Here is where the issue comes into play. The main page of the site's Action has a CustomAuthorizeAttribute decoration on it. In our CustomAuthorizeAttribute class, we have OnAuthorizion and AuthorizeCore being overrode. OnAuthorizion fires off first, however, it uses base.OnAuthorization. Once that is called, AuthorizeCore is called. In AuthorizeCore, we check for the "siteaccept" Cookie, followed by a check on the "cntPOC" Session variable. If both are there, we return true, otherwise false if either fails.
On not only my local environment but the DBA's, this works without a hitch. I see our Cookies and Session variable. However, on our DEV environment, both the Cookies and Session variable are missing. We have IE 11 configured to allow Cookies, yet we cannot get them once we leave the Action and proceed into the CustomAuthorizeAttribute.
I did find I can find the Cookie today if I check HttpContext.Current.Response instead of HttpContext.Current.Request, but that is the incorrect way to do it obviously.
Below is my code. I'm fairly certain since the code works on my local environment, it should be fine in our DEV environment. Also a quick note, our production environment does work, so the code obviously functions. It's a question now of why does the DEV environment not.
MainController.cs
[HttpPost]
public ActionResult Index(FormCollection frmCollection)
{
try
{
Response.Cookies.Remove("bracmisaccept");
HttpCookie cookie = new HttpCookie("bracmisaccept");
cookie.Value = "true";
Response.Cookies.Add(cookie);
...
//Demo Mode
var poc = new HttpCookie("cntPOC");
cookie.Value = "7578";
Response.Cookies.Add(poc);
Session["cntPOC"] = 7578;
return RedirectToAction("ApplicationSelection");
}
catch (Exception ex)
{
logger.LogError("Main Index", ex);
return PartialView(#"../Error/ExceptionHandling");
}
}
[CustomAuthorizeAttribute]
public ActionResult ApplicationSelection()
{
return View();
}
CustomAuthorizeAttribute.cs
public string RedirectUrl = "~/Main/SessionTimeout";
public string CookieExpiredRedirectUrl = "~/Main/Index";
public string AjaxRedirectUrl = "~/Error/AjaxError";
private bool _isAuthorized;
private bool _isCookieExpired;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (HttpContext.Current.Request.Cookies["siteaccept"] == null)
{
_isAuthorized = false;
_isCookieExpired = true;
return false;
}
if (HttpContext.Current.Session["cntPOC"] == null)
{
_isAuthorized = false;
return false;
}
return true;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!_isAuthorized)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
}
else
{
if(_isCookieExpired)
filterContext.RequestContext.HttpContext.Response.Redirect(CookieExpiredRedirectUrl);
else
filterContext.RequestContext.HttpContext.Response.Redirect(RedirectUrl);
}
}
}
I'm fairly certain the code is fine, but I did read in a few articles that AuthorizeCore may or may not have the Cookies and Session variables at times. I just wanted to find out if I'm wasting my time with changing the code or if it's the box we have this site on. The server is super locked down, so yeah, kind of annoying...
Edit: I have yet to figure out how to fix this yet, however, I did find if I do a publish on this code, I can enter into the site properly. I still cannot run localhost to inspect the site, but a publish fixes a few minor issues of whether things will work on this site.

How to detect if WSFederationSession has expired or ended?

I have a several methods in controller:
public ActionResult Issue()
{
var message = WSFederationMessage.CreateFromUri(HttpContext.Request.Url);
// sign in
var signinMessage = message as SignInRequestMessage;
if (signinMessage != null)
{
return ProcessWSFederationSignIn(signinMessage, ClaimsPrincipal.Current);
}
// sign out
var signoutMessage = message as SignOutRequestMessage;
if (signoutMessage != null)
{
return ProcessWSFederationSignOut(signoutMessage);
}
return View("Error");
}
And the most valuable for me in this question:
private ActionResult ProcessWSFederationSignOut(SignOutRequestMessage message)
{
FederatedAuthentication.SessionAuthenticationModule.SignOut();
var mgr = new SignInSessionsManager(HttpContext, _cookieName);
// check for return url
if (!string.IsNullOrWhiteSpace(message.Reply) && mgr.ContainsUrl(message.Reply))
{
ViewBag.ReturnUrl = message.Reply;
}
return View("Signout");
}
All works fine, but, there are interesting moment.
This thing works in both cases, if I ended session by myself, or session simply expired. Its fine but actually, I need to tell the difference between those cases, write in ViewBag something like "You are singed out" or "Session expired" depends on result and show it oy the View.
Is there are some kind of way to detect session expired situations or should it be something different?
P.S Sorry for my bad English.
Since you changed the topic I will update my answer. I haven't used WSFederatinSession but maybe you could store the inf about how session ended (in a cookie for example) and during the next request (in a global asax for example) read this inf and do what you want to do.

Check truly website address existence in all cases

I came across a problem when I started working on a project where one of the features is checking whether web address exists or not. This problem is solved but since probably no human being writes addresses like this one:http://address.somethingit has to be changed by a code either by a regex pattern or simply by string.Substring method. But than with that even nonsences like dadadafafaf will change that into http://dadadafafaf which for a link in format like this my BT internet provider will create a new website which my method checking existence of the address approves. Is there any way to edit user's input address without losing control over it?
the methid:
protected bool ZkontrolujExistenciStranky(string link)
{
try
{
var request = WebRequest.Create(link) as HttpWebRequest;
request.Method = "GET";
using (var respond = (HttpWebResponse)request.GetResponse())
{
ZiskatData(respond);
return respond.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
here is an example:
http://postimg.org/image/a4gpkvtzl/

Linq To Twitter clearing IOAuthCredentials credentials

I have a piece of functionality that creates a voice message and if authenticated through Twitter, will post a message to their Twitter account. I want the ability for the user to turn off the message posting to Twitter if they desire, so I was curious if there was a way to clear the credentials. I followed an example from the LinqToTwitter documentation:
IOAuthCredentials credentials = new SessionStateCredentials();
if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
{
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
}
auth = new WebAuthorizer
{
Credentials = credentials,
PerformRedirect = authUrl => Response.Redirect(authUrl)
};
if (!Page.IsPostBack && Request.QueryString["oauth_token"] != null)
{
auth.CompleteAuthorization(Request.Url);
}
if (auth.IsAuthorized)
{
twitterCtx = new TwitterContext(auth);
Session["TwitterContext"] = twitterCtx;
twLoginButton.Text = "Logout of Twitter";
}
I've tried the following code and variations:
credentials = null;
or
SessionStateCredentials credentials = Dispose();
But it shows errors for each of these. I was hoping someone could guide me in clearing out
IOAuthCredentials credentials = new SessionStateCredentials();
which is what I think needs to happen. Any advice would be appreciated.
The SessionStateCredentials type has properties that use Session state as their backing store. Here are a few options, with pros and cons of each:
Set the properties to null. e.g.
credentials.ConsumerKey = null;
credentials.ConsumerSecret = null;
// etc ...
This is a little ugly, though you could write a method to encapsulate the statements.
Clear out the individual Session state items. e.g.
Session.Remove("ConsumerKey");
Session.Remove("ConsumerSecret");
// etc ...
This is more explicit. However, it breaks the existing encapsulation and forces you to obtain a reference to the current session.
Derive a new class from SessionStateCredentials with a Clear method that performs the steps from one of the previous methods. This might be the cleanest option.
Here's a link to the SessionStateCredentials class so you can see the internal implementation:
http://linqtotwitter.codeplex.com/SourceControl/latest#LinqToTwitter/OAuth/SessionStateCredentials.cs

Cookie not deleting

System.Web.UI.Page oPageMy cookie is not deleting. I took a look at several articles and everything looks great, just when I step through Visual Studio (or just run under localhost) in resopnse to a button click, my cookie stays.
For whatever it is worth, I am using Visual Studio 2012 with .Net 4.0. I am debugging on localhost using the default IE (v9 on Win7/64 with all the latest updates).
public static void LoginUser(String strEmail, int iId, int iKeepDays)
{
HttpCookie oCookie = new HttpCookie("myCookie");
// Set the cookie value.
oCookie.Secure = false;
oCookie["Id"] = iId.ToString();
oCookie["Email"] = strEmail;
oCookie.Expires = DateTime.Now.AddDays(iKeepDays);
// Add the cookie.
HttpContext.Current.Response.Cookies.Add(oCookie);
}
public static void LogoutUser(System.Web.UI.Page oPage)
{
// Get the cookie.
HttpCookie oCookie = new HttpCookie("myCookie");
oCookie = HttpContext.Current.Request.Cookies["myCookie"];
if (null != oCookie)
{
// Remove the cookie.
cCookies.RemoveCookie("myCookie");
// Go back to the home page.
if (oPage.IsCallback)
ASPxWebControl.RedirectOnCallback("/");
else
HttpContext.Current.Response.Redirect("/");
}
}
/// <summary>
/// This function will be used to remove cookies value
/// </summary>
/// <param name="key"></param>
public static void RemoveCookie(String key)
{
//get cookies value
HttpCookie oCookie = null;
if (null != HttpContext.Current.Request.Cookies[key])
{
oCookie = HttpContext.Current.Request.Cookies[key];
// You cannt directly delte cookie you should set its expiry date to earlier date
oCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(oCookie);
}
}
The answer seems obvious now that I am writing it and figured it out, however I can say that the answer was not that easy to come by, obvious or not.
The code above executes on the server, but the deletion of the cookie happens on the client. Execution has to transfer to the client and then back to the server in order for the server to recognize that the cookie got deleted.
I was reading the data back within the same logout call, just in a different function. Since accepted practice states to reset the cookie, the function wrote the cookie back. The cookie was deleted and then came back. It even got a new file name. (I opened up the hidden cookie folder.)
My solution was to pass in the login state to that other function. That resolved the cookie part.
The cCookies.RemoveCookie("myCookie"); line does not call your RemoveCookie method. The line should be RemoveCookie("myCookie"); instead.

Categories