Login Control - Response.Redirect - asp.net

I have a usercontrol on a page that has a login control in it. This controls the display of another user control (if the user is not logged in they get the login control user control). I have some authentication code (see below) that runs when the user clicks the "Login" button. Basically I want it to post back to the same page so they will be logged in and able to now see the other protected user control. This code is not working. Perhaps there is something going on in another page that is making this not work, but does this code itself seem like it should work?
string userName = Membership.GetUserNameByEmail(Login1.UserName);
if (userName != null)
{
e.Authenticated = Membership.ValidateUser(userName, Login1.Password);
}
else
{
e.Authenticated = false;
}
if (e.Authenticated)
{
Login1.UserName = userName;
ImageButton loginButton = (ImageButton)Login1.FindControl("LoginButton");
if (loginButton != null)
{
//loginButton.PostBackUrl = Request.Url.ToString();
Response.Redirect(Request.Url.ToString());
}
}

The issue is the login control will itself do a redirect setting a cookie or an encrypted authentication ticket in the url (cookieless).
I think the login control has some properties where you can tell it where it will be redirecting to (which overrides the one in the web.config).

DestinationPageUrl is the property... soo Login1.DestinationPageUrl = "~/whatever.aspx";

Related

session not working asp.net

I got a problem this session :
it's not working
protected bool ValidateForm()
{
if (username.Text == "")
{
Err.Text = "please enter username" + "<br/>";
return false;
}
if (password.Text == "")
{
Err.Text = "please enter password" + "<br/>";
return false;
}
return true;
}
protected void login_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SqlDataReader rd1 = Connection.Query("select count(id) as count from sarcadmintable where username ='" + username.Text+"'",true);
if(rd1.Read())
{
if (rd1["count"].ToString() == "0") Err.Text = "please check your username" + "<br/>";
else
{
SqlDataReader rd = Connection.Query("select * from sarcadmintable where username ='" + username.Text + "'", true);
if (rd.Read())
{
if (rd["password"].ToString() != password.Text)
Err.Text = "password is not correct" + "<br/>";
else
{
Session["id"] = rd["user_id"].ToString();
Session["prev"] = rd["prev"].ToString();
if (!String.IsNullOrEmpty(Request.QueryString["Return"].ToString()))
Response.Redirect(Encryption.Decypt_URL(Request.QueryString["Return"]));
else
Response.Redirect("Main/Default.aspx");
}
}
}
}
}
}
thats the code for login its work fine
... in the header of the master.site I put this code :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["user_id"] == null || Session["user_id"].ToString() == "" || Session["user_id"].ToString() == "0") Response.Redirect("~/Login.aspx?Return=" + Encryption.Encypt_URL(Request.Url + ""));
SqlDataReader rd = Connection.Query("select firstname + ' ' + lastname as name from sarcuser where id=" + int.Parse(Session["id"].ToString()), true);
if (rd.Read())
{
label1.Text = rd["name"].ToString();
}
}
}
and in the web.config :
<!--<sessionState cookieless="true" regenerateExpiredSessionId="true" timeout="525600" mode="InProc" stateNetworkTimeout="525600"/>-->
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="he-IL"/>
</system.web>
I make the session as a comment so I take the default for session
but its not working ... every time I press login with true username and password ... its redirect me to the login page ... and take the session as empty string
but the login code is fine and recover the right value ... any help ?
Consider this code in Page_Load
if (Session["user_id"] == null || Session["user_id"].ToString() == "" || Session["user_id"].ToString() == "0") Response.Redirect("~/Login.aspx?Return=" + Encryption.Encypt_URL(Request.Url + ""));
you are checking for user_id (Session["user_id"]) while you are storing with key id (Session["id"] = ....) in login button click handler
Edit: The above solution added
Previously provided out of context answer, left below as I think it may be useful for someone to know about this
The code that you are writing in the Page_Load event handler of master page, put that code in PreRender event handler and your label will be updated properly.
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
if (Session["user_id"] == null || Session["user_id"].ToString() == "" || Session["user_id"].ToString() == "0")
Response.Redirect("~/Login.aspx?Return=" + Encryption.Encypt_URL(Request.Url + ""));
SqlDataReader rd = Connection.Query("select firstname + ' ' + lastname as name from sarcuser where id=" + int.Parse(Session["id"].ToString()), true);
if (rd.Read())
{
label1.Text = rd["name"].ToString();
}
}
}
Now why this is happening?
This is happening because the Page_Load of the master page is called before the button_Click of the content page (Refer: Sequence that events are raised for Pages, UserControls, MasterPages and HttpModules. So the execution happens as follows:
Your browser request the page (login.aspx)
Login class is instantiated
OnPreInit of Login page is invoked (which specifies the master page)
Master page is instantiated
Login.Page_Load is executed
Master.Page_Load is executed
Your browser is requested to redirect to login.aspx
Execution terminates (why? because Response.Redirect causes current thread to terminate. If you want to prevent this abnormal termination and execute the complete page, pass 'false' as second parameter to Response.Redirect(url, false)
So, as you can see above, your button_click is never executed.
How to make user login
There are multiple options:
Do not use the same master page for the login page.
On the master page, check if current page is login.aspx, ignore the checking of login
Create a master page that specify the UI design and functionality that is same across public and authenticated access (call this master1.master). Create another master page (master2.master) which specify the check for authenticated user and functionality specific to authenticated user. Now login page will user master1.master as the master page and authenticated pages will user master2.master as master page. (somewhat same as first point, but the UI design is now placed in one master page only)
Any other that developers out there could suggest
Note: As suggested above, checking for authenticated user in PreRender is not recommended at all (that was just to update the label) as it may cause some code to be executed which should be prevented in one case or the other.
I don't see any actual user.authenticate() in your code. Is your page managed by another layer of authentication somewhere? For eg. I go to an open page, enter my credentials, you check my credentials, redirect me to a page that authenticates me and then boom I am back at login page. Also you might consider moving your authentication to the page_init unless you want to do it on every postback. I think you need to post a bit more here.

LoginView Not Updating After User Login

I'm using ASP.NET Membership in order to manage a website users. But without using the specific 'Login Controls'. Actually, just applying Membership class methods in order to Create a user account and also to User login.
On the other hand, there is a LoginView control in Site.Master which is responsible to 'Welcome Username' task.
The problem is that, the LoginView control isn't updated after creating new account or any login.
Do I have to Definitely use the specific login controls?
----Also, I have set the Login Button CommandName to 'Login'!
----Should I set something like that for Create User Button?
I would appreciate any help...
The following is my code for login:
if (!Membership.ValidateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text)))
{
lblResult.Text = "Invalid user name and password.";
lblResult.Visible = true;
}
else
{
Response.Redirect("~/Default.aspx");
}
And here the registration code:
MembershipCreateStatus statusUser;
try
{
Membership.CreateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text), HttpUtility.HtmlEncode(txtEmail.Text), ddlSexQues.SelectedValue != "-1" ? ddlSexQues.Text : string.Empty, txtSecAnsw.Text == string.Empty ? string.Empty : txtSecAnsw.Text, true, out statusUser);
txtEmail.Text = string.Empty;
txtPass.Text = string.Empty;
txtRepass.Text = string.Empty;
txtSecAnsw.Text = string.Empty;
txtUserName.Text = string.Empty;
ddlSexQues.SelectedValue = "-1";
lblRsl.ForeColor = Color.Green;
lblRsl.Text = "حساب کاربری شما با موفقیت ایجاد شد.";
lblRsl.Visible = true;
}
catch (MembershipCreateUserException error)
{
lblRsl.Text = GetErrorMessage(error.StatusCode);
lblRsl.Visible = true;
}
If you're using your own login code, you'll need to persist the user's authentication information, for instance by adding a cookie to the response. The built-in controls do this automatically.
I'm assuming you're using Forms-based authentication. There's a reference to the .NET security class for Forms auth here, which details what options are available to you:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx
Look at the SetAuthCookie and RedirectFromLoginPage methods in particular.
As far as I'm aware, the CommandName property is for distinguishing between Button controls in code. As you're using your own methods to handle user creation, I don't think you need to add it to your own control. More here:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx

Passing querystring with login control in asp.net 4?

Scenario:
I am doing project in C# ASP.NET 4.
I have a page of question. When somebody clicks on question (ie a Link Button) he is redirected to page where user can give answer but first he needs to login. So I put Login to Answer button that redirects user to GuestLogin.aspx with question id like this :
protected void LoginToAnswwer_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("~/GuestLogin.aspx?qid=" + qidrequest);
//This is working OK
}
And then when I am redirected to GuestLogin.aspx, I am putting below code in LoginButton of built in Login Control.
protected void LoginButton_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("QDisplay.aspx?qid=" + qidrequest);
}
Which is not working.
Question:
How to pass querystring with login button of built login control in asp.net 4 ?
You could pass a return URL to the login page, like this:
Response.Redirect(String.Format("/auth/login.aspx?return={0}", Server.UrlEncode(Request.Url.AbsoluteUri)));
In the login page, after authenticating the user:
Response.Redirect(Request.QueryString["return"]);
Pass Parameters from One Page to Another Page using QueryString :
//Set the Querystring parameters
Note: Maximum length of the
string that can be passed through QueryString is 255.
string URL =“QueryString.aspx?Name=” + txtFirstName.Text + “&Address=” + txtAddress.Text + “&City=” + txtCity.Text ;
//After Setting the Querystring Paramter values Use Response.Redirect to navigate the page
Response.Redirect(URL);
In the Page Load Event of the Navigated
Page,You can access the querystring parameter values like below :
lblName.Text = Request.QueryString["Name"].ToString();
lblAddress.Text = Request.QueryString["Address"].ToString();
lblCity.Text= Request.QueryString["City"].ToString();
That's how you have to use QueryString for passing parameters

FormsAuthentication Rememberme

I am using forms authentication and the I wanted the remember me functionality.
How can I just retain the username alone.
I wanted the username to be stored on cookies and when the user is logged out. I want to user name to be displayed on the username text box.
Is there an example that can be provided?
In the login method (Probably your "Login" button click):
Response.Cookies["userName"].Value = txtUserName.Text;
Then on the Page_Load check for that cookie and assign the textbox a value.
if (!String.IsNullOrEmpty(Request.Cookies["userName"])) {
txtUserName.Text = Request.Cookies["userName"];
}

to display username on all aspx pages

How to Dispaly the username on all aspx pages....?
Can any one help me in this context.....
am thinking that by using "session object" we can able to do this...bt am not sure
Can any send the code or links
Assuming that you have a mechanism you can use to obtain the current user's username, you could fetch that and add code to your master page(s) to display the name. There's not really much more that can be said from your question. (Ask a vague question, get a vague answer.)
And also, if you aren't using master pages, you should be using master pages.
You can use a master page if you want to display the username on all pages.
Username can be stored in a cookie, session, etc.
Code sample:
lblUsername.Text = Session["Username"]
System.Security.Principal.IPrincipal user;
user = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity identity;
identity = user.Identity;
lblUserName.Text = identity.Name.Substring(identity.Name.IndexOf(#"\") + 1); ToString();
In First Page (Login page), store the value in Session
Session["Username"] = txtusername.text;
And rest of the pages, where you want to display the UserName
lblUser.Text = Session["Username"].Tostring();
For Logout
Session["Username"] = null;

Resources