Why FormsAuthentication.SetAuthCookie doesn't work in the IE - c#

I was using Form Authentication in my test. And also have some test user name .But found a weird problem for a specified name. That is all of test names except only one named amybeyond can works in the test.
Please help to review my code in my test.
LoginTest.aspx (This is a login form for user name and password input.)
public partial class LoginTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//after succeed validating user. then redirect to LoginSuccess.aspx page.
bool bValidate=Membership.ValidateUser("amybeyond", "11111111");
if (bValidate)
{
FormsAuthentication.SetAuthCookie("AmyBeyond", false);
Response.Redirect("LoginSuccess.aspx");
}
}
}
LoginSuccess.aspx (In this page, just simply test if current request is authenticated after redirecting.)
public partial class LoginSuccess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//the HttpContext.Current.Request.IsAuthenticated always false in the IE.
if (HttpContext.Current.Request.IsAuthenticated)
{
Response.Write("ok, you login successfully.");
}
}
}
I am sure the Membership.ValidateUser is successfully executed and return true. The problem is it can't know the authenticated status after successfully redirecting.
I didn't know if I miss something or did something wrong. If there is . Please help to tell me .thanks.
Added
I read the source code of FormsAuthentication.SetAuthCookie. and add the cookieless="UseCookies" in the Forms element of the Web.config. Hope to make sure the cookie is added to the Response(This is done by the source code HttpContext.Current.Response.Cookies.Add(cookie)). Still doesn't work.
public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
Initialize();
HttpContext current = HttpContext.Current;
if (!current.Request.IsSecureConnection && RequireSSL)
{
throw new HttpException(SR.GetString("Connection_not_secure_creating_secure_cookie"));
}
bool flag = CookielessHelperClass.UseCookieless(current, false, CookieMode);
HttpCookie cookie = GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
if (!flag)
{
HttpContext.Current.Response.Cookies.Add(cookie);
current.CookielessHelper.SetCookieValue('F', null);
}
else
{
current.CookielessHelper.SetCookieValue('F', cookie.Value);
}
}
Added
The http capturing detail shows below. in the LoginTest.aspx there is a cookie named FwLoginCookie , after redirect to LoginSuccess.aspx this cookie is lost. please help to review it .

Finally got why did this weird thing happen! It is because there is an another cookie named ACA_USER_READ_ANNOUNCEMENT sent to response. It is so large size (more than 5800bytes) that the browser (in my test it is IE) would ignore all the cookies include the Form authentication cookie(about 300bytes).
But other browser like chrome/firefox is not the same behavior with IE when encounter this case (huge cookie size.).
If it is not right . Please kindly correct me . Thanks.

Related

Make a field read only based on value in ASP.net: C#, ASP.Net

Everyone that has responded to my questions have been so very helpful and I am closing in on finishing this app. My challenge now is to make 3 fields read only based on a login.
I have the following code that does exactly what I need and assign the currently logged in user to a text field. What I want to do is make some other text fields (Read Only) if the login user does not equal a specific value. For example, if submitted_by_email_username does not equal administrator1#samplecompany.com then make the text field (Salary_in) which is a textbox, Read Only. I can read code much than I write it these days so I apologize if this is a simple request. I would like to make three fields Read Only based on that logic in the COde Behind.
protected void Page_PreInit(object sender, EventArgs e)
{
if (submitted_by_email_username != null)
{
_ = Context.User.Identity.Name;
if (User.Identity.IsAuthenticated)
submitted_by_email_username.Text = User.Identity.Name;
}
}
First of all, you don't need code in Page_PreInit 99.9% of the time in webforms. Even with dynamic controls you would only need Page_Load.
But you can make a TextBox readonly by using the Enabled property.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
submitted_by_email_username.Enabled = false;
submitted_by_email_username.Text = User.Identity.Name;
}
}

how to answer on GET request in asp.net

I have a problem and I would really appreciate your help.
An external application is sending via GET some parameters on address of my asp.net page. (something like http://mypage.com/default.aspx?id=123). I read this parameter on page load and do some other things.
If I receive the parameter correctly I must answer immediately the external application (the same which send me the parameter) with plain text 'OK'.
How to do this reply with c# asp.net ? Any sample code ? Thanks in advance for help.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Page.Request.QueryString["id"];
if (!String.IsNullOrEmpty(id))
{
SendAnswer();
}
}
private void SendAnswer()
{
// ??????? send simple reply 'OK' as plain text
}
}
You can send anything you want with Response.Write. You might have to do Response.Clear first.

redirect page on specific user detection asp.net

i would like how to implement the following in asp.net:
i have windows authentication and i would like the server to detect who the user is and redirect the page depending on the username on the page.
is there an easy way to do this?
You can get the username like...
string username = HttpContext.Current.User.Identity.Name.ToString();
Once you have the username you can redirect the page to a specific page.
Edit: You can do it in Application_AuthenticateRequest event, that is Global.asax file
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
// put code here....
}
}
For event it depends of your code.
i supose you could do such a thing in the page_load event if you have any doubt you should check the ASP.NETlifecylce http://www.google.fr/search?sourceid=chrome&ie=UTF-8&q=asp.net+lifecycle
BTW you can use Response.redirect to redirect the user.
pretty straightforward
protected void Page_Load(object sender, EventArgs e)
{
string username = HttpContext.Current.User.Identity.Name.ToString();
if (username == "someusername")
{
Response.Redirect("someaspxfile.aspx");
}
}
If you are looking for picking up the control with username in it, it will be available in the request. You can pick the data from request

Checking Page.IsPostBack in user controls

Is it recommended to check the Page.IsPostBack in a user control Page_Load Event like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
I am getting wierd results
Edit ~ Here is the thing. When the main form is loaded, I use Request.QueryString to get the customer id which I then place in a SESSION variable.
On the control Load event I read the SESSION variable to get the data for that customer. So, do I need to check PostBack at the control level?
Edit ~ Here is the load event of the control
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Getting and storing the customer account number
if (string.IsNullOrEmpty((string)Session["CustomerNumber"]))
{
Session["CustomerNumber"] = cust.GetCustomerNumber(myHelper.GetCustomerIDFromQueryString());
LoadProductData();
}
}
}
Here is the myHelper Class
static class myHelper
{
public static Guid GetCustomerIDFromQueryString()
{
//Getting the GUID (used as customerid in CRM) from the URL request of the selected account.
return Sql.ToGuid(System.Web.HttpContext.Current.Request["ID"]);
}
}
}
If you use "!IsPostBack" in page load, when the user click other control it do a postBack, so you don't get your data.
I hope that helps you.
Just checking it for no reason? Absolutely not. If you should do something only on first load and not on subsequent post backs then it's the pattern that should be used.
Are you sure that you will always have a "CustomerNumber" already stored in the Session by the time you get to your page? Is there any rhyme or reason that you can find as to when you get data and when you don't?

Cookie only displayed on refresh?

I have some trouble understanding this one so here it is.
I'm trying to set a cookie and display the value on the page using ASP.NET + C#.
here's my code:
protected void lbChangeToSmall_Click(object sender, EventArgs e)
{
Response.Cookies["fontSize"].Value = "small";
}
and
<asp:LinkButton runat="server" id="lbChangeToSmall" Text="A" CssClass="txt-sm" OnClick="lbChangeToSmall_Click"></asp:LinkButton>
And finally
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write( Request.Cookies["fontSize"].Value);
}
}
When I click on the button, nothing is displayed on the page, but the cookie is actually set. If I refresh the page, the cookie displays.
So it seems that the cookie is set correctly but the application is not able to read it right away.
I tried to get rid of the if(postBack):
protected void Page_Load(object sender, EventArgs e)
{
Response.Write( Request.Cookies["virgilFontSize"].Value);
}
but it didn't change a thing.
What am I doing wrong?
Thanks!
The lblChangeToSmall_Click event is fired after the Page_Load event. Therefore the cookie write won't be available on the Request until the subsequent postback.
It will be avaialable on the client immediately though.
The first time, the request has no cookies (yet); it will only have them the second time around, after the response has set them. So your code has to deal with the possibility that Request.Cookies just may not have a "fontSize" entry, and provide the proper default when that is the case. For example:
HttpCookie cookie = Request.Cookies.Get("fontSize");
// Check if cookie exists in the current request.
if (cookie == null)
{
Response.Write( "Defaulting to 'small'.");
}
else
{
Response.Write( Request.Cookies["fontSize"].Value);
)

Categories