ASP.NET Set cookie ONLY if empty Value - c#

I am trying to set a cookie when the user access my webpage. The value of the cookie is a unique number that I store on my database to keep track of when the user comes back to my website. I set the cookie in my global.asax as follow:
void Application_BeginRequest()
{
string cookievalue = "";
string a = "";
try
{
a = GetCookie();
if (!string.IsNullOrEmpty(a))
{
cookievalue = a;
}
else
{
cookievalue = SetCookie();
}
}
catch (Exception ex)
{
}
}
In BeginRequest() I only want to check if the cookie exist. If exist, then do nothing and keep the value that is already inside the cookie. If it doesn't exist, then set the cookie and add a value.
public static string GetCookie()
{
string cookievalue = "";
try
{
if (HttpContext.Current.Request.Cookies["TestCookie"] != null)
cookievalue = HttpContext.Current.Response.Cookies["TestCookie"].Value;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
public static string SetCookie()
{
string cookievalue = "";
try
{
HttpCookie myCookie = new HttpCookie("TestCookie");
// Set the cookie value.
myCookie.Value = "1234"; //1234 is my unique number
myCookie.Expires = DateTime.Now.AddYears(50);
HttpContext.Current.Response.Cookies.Add(myCookie);
cookievalue = id;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
The problem is that everytime I reload the page, "TestCookie" gets rewritten with a new value. I have been reading the MSDN about how cookies are stored in ASP.NET and according to the instructions, the way it is supposed to work fine. I must be doing something wrong that I cannot see it. I had all this code inside a normal page e.g. test.aspx.cs to test it early but had the same result and decided to move it to the application level and see if that would make any difference but it did not :(.

Related

Debug SSRS C# DLL Called from Java Application

I am in the process of implementing Microsoft SQL Service Reporting Services for my company. SSRS will be called from our company's Java web app. We have decided to use a single sign-on approach when requesting a report from SSRS from the Java web app. With that being the case, we are utilizing forms authentication via a custom security extension to enable single sign-on. As you may already know, after the user submits the UILogon.aspx page, a ticket is created and placed in the cookie called sqlAuthCookie. This cookie (ticket) is then used for authorization whenever the user makes any subsequent requests to SSRS.
The problem I am having is that it appears that the form authentication code, that is written in C# and resides on the SSRS server as a .dll, is not creating a ticket and placing it in the sqlAuthCookie cookie. I've inspected the sqlAuthCookie cookie within the Java web app. by accessing the RSAuthenticationHeader in the response header and the sqlAuthCookie cookie does not contain a value.
So what I want to know is if there is a way that I can put the form authentication code, which is a .dll, in debug within Visual Studio, so that when I log into SSRS from the Java web application, I can step through this code to verify whether or not it is creating the ticket for the cookie.
Please let me know if you require a code snippet.
Code
private void BtnLogon_Click(object sender, System.EventArgs e)
{
bool passwordVerified = false;
try
{
ReportServerProxy server = new ReportServerProxy();
string reportServer = ConfigurationManager.AppSettings["ReportServer"];
string instanceName = ConfigurationManager.AppSettings["ReportServerInstance"];
// Get the server URL from the report server using WMI
server.Url = AuthenticationUtilities.GetReportServerUrl(reportServer, instanceName);
server.LogonUser(TxtUser.Text, TxtPwd.Text, null);
passwordVerified = true;
}
catch (Exception ex)
{
lblMessage.Text = string.Format(CultureInfo.InvariantCulture, ex.Message); ;
return;
}
if (passwordVerified == true)
{
lblMessage.Text = string.Format(CultureInfo.InvariantCulture,
UILogon_aspx.LoginSuccess);
string redirectUrl =
Request.QueryString["ReturnUrl"];
if (redirectUrl != null)
HttpContext.Current.Response.Redirect(redirectUrl, false);
else
HttpContext.Current.Response.Redirect(
"./Folder.aspx", false);
}
else
{
lblMessage.Text = string.Format(CultureInfo.InvariantCulture,
UILogon_aspx.InvalidUsernamePassword);
}
}
}
// Because the UILogon uses the Web service to connect to the report server
// you need to extend the server proxy to support authentication ticket
// (cookie) management
public class ReportServerProxy : ReportingService2005
{
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)HttpWebRequest.Create(uri);
// Create a cookie jar to hold the request cookie
CookieContainer cookieJar = new CookieContainer();
request.CookieContainer = cookieJar;
Cookie authCookie = AuthCookie;
// if the client already has an auth cookie
// place it in the request's cookie container
if (authCookie != null)
request.CookieContainer.Add(authCookie);
request.Timeout = -1;
request.Headers.Add("Accept-Language",
HttpContext.Current.Request.Headers["Accept-Language"]);
return request;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
string cookieName = response.Headers["RSAuthenticationHeader"];
// If the response contains an auth header, store the cookie
if (cookieName != null)
{
Utilities.CustomAuthCookieName = cookieName;
HttpWebResponse webResponse = (HttpWebResponse)response;
Cookie authCookie = webResponse.Cookies[cookieName];
// If the auth cookie is null, throw an exception
if (authCookie == null)
{
throw new Exception(
"Authorization ticket not received by LogonUser");
}
// otherwise save it for this request
AuthCookie = authCookie;
// and send it to the client
Utilities.RelayCookieToClient(authCookie);
}
return response;
}
private Cookie AuthCookie
{
get
{
if (m_Authcookie == null)
m_Authcookie =
Utilities.TranslateCookie(
HttpContext.Current.Request.Cookies[Utilities.CustomAuthCookieName]);
return m_Authcookie;
}
set
{
m_Authcookie = value;
}
}
private Cookie m_Authcookie = null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
internal sealed class Utilities
{
internal static string CustomAuthCookieName
{
get
{
lock (m_cookieNamelockRoot)
{
return m_cookieName;
}
}
set
{
lock (m_cookieNamelockRoot)
{
m_cookieName = value;
}
}
}
private static string m_cookieName;
private static object m_cookieNamelockRoot = new object();
private static HttpCookie TranslateCookie(Cookie netCookie)
{
if (netCookie == null)
return null;
HttpCookie webCookie = new HttpCookie(netCookie.Name, netCookie.Value);
// Add domain only if it is dotted - IE doesn't send back the cookie
// if we set the domain otherwise
if (netCookie.Domain.IndexOf('.') != -1)
webCookie.Domain = netCookie.Domain;
webCookie.Expires = netCookie.Expires;
webCookie.Path = netCookie.Path;
webCookie.Secure = netCookie.Secure;
return webCookie;
}
internal static Cookie TranslateCookie(HttpCookie webCookie)
{
if (webCookie == null)
return null;
Cookie netCookie = new Cookie(webCookie.Name, webCookie.Value);
if (webCookie.Domain == null)
netCookie.Domain =
HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
netCookie.Expires = webCookie.Expires;
netCookie.Path = webCookie.Path;
netCookie.Secure = webCookie.Secure;
return netCookie;
}
internal static void RelayCookieToClient(Cookie cookie)
{
// add the cookie if not already in there
if (HttpContext.Current.Response.Cookies[cookie.Name] == null)
{
HttpContext.Current.Response.Cookies.Remove(cookie.Name);
}
HttpContext.Current.Response.SetCookie(TranslateCookie(cookie));
}
}

ASPX Cookies lost

I have an issue with ASP.NET cookies being lost between requests.
I have an ASCX control which has multiple filtering checkboxes. I can check/uncheck these checkboxes and then I click a . In this applyFilters method, I am setting cookies based on whether the checkboxes are checked/unchecked. The code that does this is :
public void setFilterCookie(string name, string val)
{
if (!String.IsNullOrEmpty(val) && (val != null && !val.Equals("-1")))
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
HttpCookie cookie = new HttpCookie(name, val);
cookie.Expires = DateTime.Now.AddDays(5);
response.Cookies.Add(cookie);
}
else
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
}
}
After the cookies are set, I want to databind a grid from the parent container of the control. In this databind method I am reading the cookies using the following method :
public string getCookie(string cookieName)
{
if (isNotNullOrEmpty(cookieName))
return request.Cookies[cookieName].Value.ToString().Trim();
else
return null;
}
The problem is that when I am setting the cookies, I can see the values being set (e.g. response.Cookies["Domain"] = "5") but when I am reading them the value is string empty.
Can somebody tell me what is wrong?
Thank you
You shouldn't be removing request cookies and adding response cookies with the same name multiple times. This should work.
public void setFilterCookie(string name, string val)
{
var cookieValue = string.Empty;
var expires = 0;
if (!string.IsNullOrWhiteSpace(val) && !val.Equals("-1"))
{
cookieValue = val;
expires = 5;
}
else
{
expires = -2;
}
var cookie = new HttpCookie(name, cookieValue) {Expires = DateTime.Now.AddDays(expires)};
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

Cannot retrieve cookie value

Am storing and retreiving the cookie using the coding
public static void SetCookie(string key, string value, int dayExpires)
{
HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));
encodedCookie.Expires = DateTime.Now.AddDays(dayExpires);
HttpContext.Current.Response.Cookies.Remove(key);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
public static string GetCookie(string key)
{
string value = string.Empty;
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
if (cookie != null)
{
// For security purpose, we need to encrypt the value.
HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
value = decodedCookie.Value;
}
else
{
SetCookie("currency", "GBP", 1);
if (key.ToUpper() == "CURRENCY")
value = "GBP";
else if (key.ToUpper() == "COUNTRYCODE")
value = "GB";
}
return value;
}
}
am able to store the cookie and also when i try to get the value of currency from the cookie using HttpContext.Current.Request.Cookies[key] where key has currency am getting the value as ""
in the image below you can have the look at the cookies stored
here you can see that you can currency repeated twice. In key [4] currency is "" where as i have my cookie value in key [6]. Any help why the currency is repeated twice when i am removing the key and then adding the key in the immediate lines.
For test purpose i have placed the set and get in the immediate lines. code below
CookieStore.SetCookie("currency", CurrencyCode, 1);
string currencycookie=CookieStore.GetCookie("currency");
Ultimately i must have only one currency where i have the unique key there.
Thanks.
Removing the key like this will not help you , remove the cookie set in the client browser. Either you have to set the expiry date in the past for the existing key. Better solution is to check if the key is available update the value of the cookie rather than removing and adding it.
if (Request.Cookies[key] != null)
{
Response.Cookies[key].Value = "NEW VAalue"
}
else
// create the new cookie key.
See my updated code with logic of removing and adding the new value
if (Request.Cookies["Test"] == null)
{
HttpCookie testCookie = new HttpCookie("Test");
testCookie.Value = "1";
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
}
else
{
var c = Request.Cookies["Test"];
c.Expires = DateTime.Now.AddDays(-10);
Response.Cookies.Add(c);
HttpCookie testCookie = new HttpCookie("Test");
testCookie.Value = "2";
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
}
I have updated your method.
public static void SetCookie(string key, string value, int dayExpires)
{
if (Request.Cookies[key] != null)
{
var c = HttpContext.Current.Request.Cookies[key];
c.Expires = DateTime.Now.AddDays(-10);
HttpContext.Current.Response.Cookies.Add(c);
}
HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));
encodedCookie.Expires = DateTime.Now.AddDays(dayExpires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}

How to validate password when TextMode="Password"

I'm building a web application using the default master template in VS2010 - very new to doing this. I'm also using the Login.aspx page, but instead of using the built in user validation, my user info is in a database table. So Following instructions I found, I'm doing something wery similar to this:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean bauthenticated = false;
bauthenticated = isValidUser(Login1.UserName, Login1.Password);
if (bauthenticated)
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
The problem is that I put the method isValidUser in a .dll so it could be used elsewhere, and it is not receiving the password because the default behaivor is to blank it out. I even tried to set a string variable to Login1.Password, and pass the variable without success. I understand why this is happening, but can't find any info as to how to do this correctly. Do I need to put the user name and password into an object and pass that to my class constructor? I really don't want to connect to my database from every Login.aspx page I create to avoid sending the password over http.
Try to use the following code.
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(LoginUser.UserName.Trim(), LoginUser.Password.Trim(), out dtUserDetails))
{
AuthUser au = new AuthUser();
if (dtUserDetails.Rows.Count > 0)
{
DataRow DR = dtUserDetails.Rows[0];
au.UserID = Convert.ToInt32(DR["UserID"].ToString());
au.UserNo = DR["UserNo"].ToString();
au.UserName = DR["UserName"].ToString();
au.Password = DR["Password"].ToString();
}
string userData = au.ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Version number
LoginUser.UserName.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie
(FormsAuthentication.FormsCookieName, eticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", LoginUser.UserName.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
LoginUser.FailureText = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
dtUserDetails is a out parameter which contains the user details like password,username,etc.. on successful login.datatable returns empty if invalid login.with in userData string all those information will be available.then u can retrieve those from any page using User Authenticated Ticket

How to read cookies4.dat file using c#?

I want to display the list of cookies, i am unable to read this file. can anyone please guide me on reading data from this file(cookies4.dat).
It is from opera browser.
Thanks in Advance.
Have you tried the documentation?
This CodeProject article shows details on reading cookies for the major browsers, including Opera. Unfortunately it doesn't give much details on how the magic is done but you should be able to download the code and check it out.
A couple of methods included:
private static string GetOperaCookiePath()
{
string s = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
s += #"\Opera\Opera\cookies4.dat";
if (!File.Exists(s))
return string.Empty;
return s;
}
private static bool GetCookie_Opera(string strHost, string strField, ref string Value)
{
Value = "";
bool fRtn = false;
string strPath;
// Check to see if Opera Installed
strPath = GetOperaCookiePath();
if (string.Empty == strPath) // Nope, perhaps another browser
return false;
try
{
OpraCookieJar cookieJar = new OpraCookieJar(strPath);
List<O4Cookie> cookies = cookieJar.GetCookies(strHost);
if (null != cookies)
{
foreach (O4Cookie cookie in cookies)
{
if (cookie.Name.ToUpper().Equals(strField.ToUpper()))
{
Value = cookie.Value;
fRtn = true;
break;
}
}
}
}
catch (Exception)
{
Value = string.Empty;
fRtn = false;
}
return fRtn;
}
http://www.opera.com/docs/operafiles/#cookies

Categories

Resources