In my project, I have written code for creating a cookie.
I need to retrieve its value on another page. Here's what I've tried, on the Login.aspx button click event:
Guid guid_string_Id = System.Guid.NewGuid();
string newID = guid_string_Id.ToString();
Response.Cookies["name"]["Font"] = newID;
Response.Redirect("page2.aspx");
On page load for page2.aspx,
if (Request.Cookies["name"] != null)
{
string new_ID;
if (Request.Cookies["name"]["Font"] != null)
{
new_ID = Request.Cookies["name"]["Font"];
}
}
else
{
Response.Redirect("Login.aspx");
}
I always find that cookies value remains same .what will be the problem?
In my web.config, I have set:
<sessionState mode="InProc" regenerateExpiredSessionId="true" stateNetworkTimeout="30" sqlCommandTimeout="30" cookieless="false" timeout="30">
</sessionState>
On your Login.aspx page you just need to add a cookie to the cookies collection:
Guid guid_string_Id = System.Guid.NewGuid();
string newID = guid_string_Id.ToString();
var cookie = new HttpCookie("font", newID);
Response.Cookies.Add(cookie);
Response.Redirect("page2.aspx");
Related
I am testing something quick, but I can't save cookies into browser. When I check cookies in browser they are not there. My code:
private void WriteCookie(string setting, string settingValue)
{
HttpCookie myCookie = new HttpCookie(setting);
// Set the cookie value.
myCookie.Value = settingValue;
// Set the cookie expiration date.
myCookie.Expires = DateTime.Now.AddDays(10);
// Add the cookie.
Response.Cookies.Add(myCookie);
}
private string ReadCookie(string setting)
{
HttpCookie myCookie = new HttpCookie(setting);
myCookie = Request.Cookies[setting];
// Read the cookie information and display it.
if (myCookie != null)
return myCookie.Value;
return null;
}
I am setting cookie in MVC action #1:
if(page != null)
{
WriteCookie("page", page.ToString());
}
if (pageDraft != null)
{
WriteCookie("pageDraft", pageDraft.ToString());
}
Then I read:
if (ReadCookie("page") != null)
page = Convert.ToInt32(ReadCookie("page"));
if (ReadCookie("pageDraft") != null)
pageDraft = Convert.ToInt32(ReadCookie("pageDraft"));
When page is refreshed, I lose cookies. Why?
Probslem was web.config:
<httpCookies requireSSL="true" />
Changed to:
<httpCookies httpOnlyCookies="true" requireSSL="false" />
Good afternoon.
I have a situation with a SSL web application written in C# in that if I log in and navigate to a secure page, close my browser and open it again after the login has expired, the content that was shown when closing the browser still appears.
In other words, if the login cookie expires after 30 minutes, and I close the browser and re-open it (restoring my tabs) after 30 minutes, the page that I was viewing still appears and not the expected login page.
If I click on a link after re-opening the browser that is supposed to take me to another secure location, I am redirected to the login page, but I'd like to prevent the previous page content from being shown again since it could contain sensitive data.
The page content is set to expire after 30 minutes and the user login cookie is set to expire after 30 minutes as well. (See images below)
I'm not sure how to force the login screen to appear when re-opening a browser. Thoughts or help would be greatly appreciated!
EDIT: Relevant content of web.config if it will help.:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
[REMOVED]
<authentication mode="Forms">
<forms path="/" cookieless="UseCookies" loginUrl="~/Account/Login.aspx" name="[REMOVED]" requireSSL="true" timeout="30" />
</authentication>
[REMOVED]
</system.web>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:30:00" />
</staticContent>
[REMOVED]
</system.webServer>
[REMOVED]
</configuration>
OnLoad Method from the Site.Master page:
protected void Page_Load(object sender, EventArgs e)
{
/*
* See if the user has read the service agreement, if not, send the user to the service agreement page.
* Do NOT process this if it is being called from the service agreement page!
* If you do, we will end up with an infinite loop and infinite loops are bad mmmkay?
*/
if (!Profile.IsAnonymous && !Roles.IsUserInRole("Administrator"))
{
if (!Profile.ServiceAgreementStatusOkay())
{
if (Page.Request.RawUrl != #"/Account/KB/SA/")
{
Response.Redirect("/Account/KB/SA/");
}
}
}
// only check messages if the user isn't anonymous
if (!Profile.IsAnonymous)
{
int UnreadMessageCount = 0;
SqlDataSourceMessageCount.SelectParameters["UserId"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString();
SqlDataSourceMessageList.SelectParameters["UserId"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString();
Repeater MessageListRepeater = ((Repeater)LoginViewUserMenu.FindControl("RepeaterMessages"));
SqlDataReader CountReader = null;
DataView MessageListDataView = new DataView();
try
{
CountReader = (SqlDataReader)SqlDataSourceMessageCount.Select(DataSourceSelectArguments.Empty);
if (CountReader.HasRows)
{
CountReader.Read();
UnreadMessageCount = CountReader.SafeGetInt32(0);
if (UnreadMessageCount != 0)
{
((Literal)LoginViewUserMenu.FindControl("LiteralMessageCount")).Text = UnreadMessageCount.ToString();
}
else
{
((Literal)LoginViewUserMenu.FindControl("LiteralMessageCount")).Text = string.Empty;
}
}
SqlDataSourceMessageList.FilterParameters.Clear();
SqlDataSourceMessageList.FilterExpression = string.Empty;
SqlDataSourceMessageList.FilterParameters.Add("IsRead", "false");
SqlDataSourceMessageList.FilterExpression = "IsRead = {0}";
MessageListDataView = (DataView)SqlDataSourceMessageList.Select(DataSourceSelectArguments.Empty);
MessageListRepeater.DataSource = MessageListDataView;
MessageListRepeater.DataBind();
}
catch (Exception ex)
{
ErrorNotifier Err = new ErrorNotifier();
Err.Notify(ex, HttpContext.Current.Request.Url.AbsoluteUri.ToString());
throw;
}
finally
{
if (CountReader != null)
{
if (!CountReader.IsClosed)
{
CountReader.Close();
}
}
}
}
// set the value of the bug report path.
TextBoxPath.Text = Page.Request.RawUrl;
// set footer stuff.
AppCopyrightDate.Text = AppAttributes.GetCopyrightString();
LiteralVersionNumber.Text = AppAttributes.AppVersion.ToString();
// set theme info.
ThemeManager TM = new ThemeManager();
if (Request["ThemePreview"] == null)
{
LiteralTheme.Text = TM.GetThemeLink(Profile.UX.Theme);
}
else
{
LiteralTheme.Text = TM.GetThemeLink(Request["ThemePreview"]);
}
}
I don't want to show mail id in my application code. I want to give text box and what ever email id I will give it should be stored in web.config file for ever until I change it.
string store= "kumar#gmail.com";
ConfigurationManager.AppSettings["MailId"] = store;
string message1 = ConfigurationManager.AppSettings["MailId"];
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2001"/>
<add key="MailId" value="krishnamohan.p#sun.com" />
</appSettings>
string MailID = ConfigurationManager.AppSettings["MailId"];
Create a cookie
HttpCookie mailCookie= new HttpCookie("mailCookie");
Add key-values in the cookie
mailCookie.Values.Add("MailID", MailID);
set cookie expiry date-time. Keep it max value.
mailCookie.Expires = DateTime.MaxValue;
Most important, write the cookie to client.
Response.Cookies.Add(mailCookie);
Read the cookie from Request.
HttpCookie mailCookie= Request.Cookies["mailCookie"];
if (mailCookie== null)
{
//No cookie found or cookie expired.
}
Cookie is found.
if (!string.IsNullOrEmpty(mailCookie.Values["MailID"]))
{
string MailID= mailCookie.Values["MailID"].ToString();
}
pseudo code:
Code to ADD cookie
HttpCookie e = new HttpCookie("d");
e.Value = "set-Email-Id";
e.Expires = DateTime.Now.AddDays(30); // expires after 30 days
HttpContext.Current.Response.Cookies.Add(e);
Code to Read ( get ) cookie by it name
HttpCookie ck_d = Request.Cookies["d"];
if(ck_d!=null)
{
// logic here
}
HttpCookie Cookie = new HttpCookie("cksunlightitmailid");
Cookie.Value = txtSunlightitmailid.Text.Trim();
Cookie.Expires = DateTime.MaxValue; // never expire
HttpContext.Current.Response.Cookies.Add(Cookie);
HttpCookie ck_d = Request.Cookies["cksunlightitmailid"];
if (Request.Cookies["cksunlightitmailid"] != null)
{
lblSunlightitmailid.Text = "Ur current email id :" + Request.Cookies["cksunlightitmailid"].Value;
//Or Write ur own code here
}
I store the cookies when someone is logging in, as below:
List<User> listUser;
//returns 1 user
foreach(User u in listUser)
{
HttpCookie cookieNickname = new HttpCookie("UserNickname");
cookieNickname.Value = u.Nickname.ToString();
cookieNickname.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookieNickname);
HttpCookie cookiePassword = new HttpCookie("UserPassword");
cookiePassword.Value = u.Password;
cookiePassword.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookiePassword);
}
When someone visits the site again, I want to read data from the database which is associated with usernickname-cookie and userpassword-cookie.
Then I want to show the firstname and lastname on a label.
This is what I tried:
List<User> cookieLoggedInUser;
if (Request.Cookies["UserNickname"] != null && Request.Cookies["UserPassword"] != null)
{
//returns 1 user
cookieLoggedInUser = Database.SignIn(Request.Cookies["UserNickname"].ToString(), Request.Cookies["UserPassword"].ToString());
if (cookieLoggedInUser.Count > 0)
{
foreach (User u in cookieLoggedInUser)
{
lblFirstName.Text = u.FirstName;
lblLastName.Text = u.LastName;
}
}
}
But both of the Request.Cookies return null.
Why is that happening?
I wouldn't recommend the approach you took other then for experimeting purposes as it has big security risk.
To make your curent solution work check that you are creating cookies in the same domain where you consume them.
If it is not the case, browser will not send cookies to the other domain.
You can make the sign-in cookie permanent using a technique like this:
protected void Login1_OnLoggedIn(object sender, EventArgs e)
{
CheckBox Remember = (CheckBox)((Login)sender).FindControl("Remember");
if (Remember.Checked)
{
FormsAuthenticationTicket t = new FormsAuthenticationTicket(2, Login1.UserName, DateTime.Now, DateTime.Now.AddYears(5), true, "");
string data = FormsAuthentication.Encrypt(t);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, data);
authCookie.HttpOnly = true;
authCookie.Domain = "";
authCookie.Expires = t.Expiration;
Response.Cookies.Remove("FORMAUTH");
Response.Cookies.Add(authCookie);
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
}
This assumes the site is using asp.net membership services.
The line that says Response.Cookies.Remove("FORMAUTH"); should match the cookie name you have set up in your web.config under this section:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/Login.aspx" name="FORMAUTH"/>
</authentication>
Wire this up to the OnLoggedIn event of your <asp:Login> control and when the user clicks Remember Me they stay logged in.
This is a lot safer than the alternative which you propose (storing unencrypted passwords in cookies).
I am creating a login and the storing the user details in a cookie using this code
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
//string useremail = Convert.ToString(txtUserName.Value);
Session.Add("useremail", txtUserName.Value);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
I am also creating a session Session.Add("useremail", txtUserName.Value);
After succesfull authentication it is redirected to user.aspx
I want to read the useremail value in the user.aspx page but when I tried to access the value in the user page it is not showing useremail field.
protected void Page_Load(object sender, EventArgs e)
{
if
(Session["useremail"] == null) Response.Redirect("Home.aspx");
else
BindGridView(useremail);
}
And this is my webconfig:
<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>
Correct me if i am doing any wrong. And also please tell me how to pass the useremail value to the user.aspx page so that I can pass that value to gridview function
Just change it to
protected void Page_Load(object sender, EventArgs e)
{
if (Session["useremail"] == null)
Response.Redirect("Home.aspx");
else
BindGridView((string)Session["useremail"]);
}
You can add an object to the session state like this:
Session["useremail"] = "john.smith#microsoft.com";
You can then retrieve it in the following manner:
var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
//...
}
else
{
BindGridView(useremail);
}
If the item "useremail" is not present in the session state the useremail variable will be set to null otherwhise it will contain the e-mail address.
You are getting confused with relationship between authentication, session state and cookies.
In ASP.NET, Session State and Forms Authentication are not linked i.e. their scope are different. You can have some session state for un-authenticated user. Session and forms authentication uses different cookies for tracking purposes and the cookie management is more or less automatic and you don't really need to write code to manage it as you have done. Besides, what you store in the cookie has no bearing on what goes in the session state. Its also possible to have both session and forms authentication to get working w/o cookies. So code such as below should work for session state
Session["key"] = "put your data here";
// retrieve the data elsewhere
var data = Session["key"];