There is a Login control on my ASP.NET (2.0) page. I handle LoggingIn event like this:
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
// go to database and find this user
if (userTable != null && userTable.Rows.Count > 0)
{
int userID = Convert.ToInt32(userTable.Rows[0]["UserID"]);
HttpCookie userIdCookie = new HttpCookie("UserID", userID.ToString());
Response.AppendCookie(userIdCookie);
}
else
{
e.Cancel = true;
}
}
User found in database. And at the end of this function e.Cancel still set to false. But then occured LoginError. LoggedIn doesn't occured. And FailureText appears on the page. I don't know how to debug this :(
Have you also handled the Authenticate event?
<asp:Login id="Login1" runat="server"
OnAuthenticate="MyOnAuthenticate">
private void MyOnAuthenticate(object sender, AuthenticateEventArgs e)
{
bool isAuthenticated = false;
isAuthenticated = YourAuthenticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = isAuthenticated;
}
private bool YourAuthenticationMethod(string UserName, string pwd)
{
// Insert code that implements a site-specific custom
// authentication method here.
}
LoginControl's Authenticated event on MSDN
Related
I want to get the username after login but it doesn't work.
public partial class Login : System.Web.UI.Page
{
string strUser;
protected void Login1_LoggedIn(object sender, EventArgs e)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
}
This is my error:
Membership.GetUser().UserName is null, because the new principal object is not attached to the current HttpContext object yet.
So you need to explicitly retrieve that recently logged-in user using username from Login control.
Update: Credit to jadarnel27
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get the username from login control and retrieves the user info explicitly
Membership user = Membership.GetUser(Login1.Username);
...
}
You need to check and make sure the user's login was successful. It looks like you're just using standard ASP.NET membership, so this should work:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if(e.Authenticated)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
else
{
strUser = "Login Failed!";
}
}
It's been a while since I worked with these controls, but you might need to determine the value of e.Authenticated yourself first and set it. If so, you need to put this before the if-block I wrote above:
bool authenticated = Membership.ValidateUser(Login1.UserName, Login1.Password);
e.Authenticated = authenticated;
I think vanilla ASP.NET membership handles that part for you; if you were using a custom authentication scheme, you would definitely need to do that step.
I am coding an ASP.NET website with C# and Entity Framework.
I stored into a session a Login class I created. The class contains information such as the NetID, the Roles available to the user, and the role the user selects to login as.
The problem I am encountering is that whenever I try to get the information that is stored in the session inside of a Button_Click event, it seems to not get the information. I do not know if this is allowed. However, I also put the Login variable that contains the user information as public variable for any function inside the partial class to access and I still have the same problem accessing the information inside a Button_Click event. When I get the Session information inside the Page_Load event, I am able to get the values that were placed inside that Session.
The following is the code of my program.
public partial class Private_HomePagePortal : System.Web.UI.Page
{
Login SysUser = new Login();
protected void Page_Load(object sender, EventArgs e)
{
string[] Roles;
SysUser.Ticket = Request.QueryString["casticket"];
SysUser.GetNetID();
if (SysUser.Authenticate(SysUser.NetID))
{
SysUser.GetRoles(SysUser.NetID);
Roles = SysUser.Roles;
CasOut.Text = "Welcome <b>" + SysUser.NetID + "</b>! You are now Logged in! " + "Please choose a role you would like to sign in as." + "<br>" + "<br>";
foreach (string item in Roles)
{
if (item == "Admin")
{
Admin.Visible = true;
Admin.CssClass = "btn btn-danger";
AdminBreak.Text = "<br><br>";
}
if (item == "SuperAdmin")
{
SuperAdmin.Visible = true;
SuperAdmin.CssClass = "btn btn-danger";
SuperAdminBreak.Text = "<br><br>";
}
if (item == "Member")
{
Member.Visible = true;
Member.CssClass = "btn btn-danger";
MemberBreak.Text = "<br><br>";
}
if (item == "Convener")
{
Convener.Visible = true;
Convener.CssClass = "btn btn-danger";
ConvenerBreak.Text = "<br><br>";
}
if (item == "ITAdmin")
{
ITAdmin.Visible = true;
ITAdmin.CssClass = "btn btn-danger";
}
}
else
CasOut.Text = "You are not in the IUCommittee System!!!! If you believe this is an error, contact the IT Administrator for assistance.";
Session["Login"] = SysUser;
Login User = (Login)Session["Login"]; //Used to test information is actually in the Session
CasOut.Text = User.NetID;
}
protected void Admin_Click(object sender, EventArgs e)
{
Login User = (Login)Session["Login"];
User.SelectedRole = "Admin";
CasOut.Text = User.NetID + User.SelectedRole;
Session["Login"] = User;
}
}
I would greatly appreciate the help.
Page_Load code will be executed each time when you press the button and in that case value of QueryString value will be erased.
Be ensure that code in page_load gets executed once per page postback (use IsPostBack) or something like:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Login"]==null)
{
string[] Roles;
....
CasOut.Text = User.NetID;
}
}
OR
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string[] Roles;
....
CasOut.Text = User.NetID;
}
}
I am using session to authenticate a user. I have 2 web pages in my project. One is webform and other one is EntryForm.aspx and other one is log.aspx
In log.aspx i have done
protected void Button1_Click(object sender, EventArgs e)
{
user_login loginu = new user_login();
String uid_db = loginu.login(this.DropDownList1, this.TextBox1, this.TextBox2, this.Label5);
if (uid_db == "invalid")
{
Label5.Visible = true;
Label5.Text = "Invalid Login";
}
else
{
string uname = uid_db.Substring(0, uid_db.IndexOf(",")).Trim();
string[] tokens = uid_db.Split(',');
string dbname = tokens[tokens.Length - 1];
Session["login"] = uname;
Session["db"] = dbname;
Response.Redirect("EntryForm.aspx");
}
}
In class user_login I am taking the password stored in the database and matching it with the value entered by user. if it finds a value i redirect it to EntryForm.aspx. In which i check for session variable as follows
protected void Page_Load(object sender, EventArgs e)
{// CHEK SESSION VARIABLE AND LOAD dropdownlist1 WITH VALUES
if (!IsPostBack)
{
String DB = "";
String AccountID = "";
if (Session["login"] != null && Session["db"] != null)
{
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
}
else
{
Response.Redirect("log.aspx");
}
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
}
This is what i have done do authenticate a user. On server i have done the following configuration:
I have done no settings in Global.asax nor anything is web.config . I have seen many forum wherein Global.asax and web.config is configured.
I want to know what do i need to do in my project in order to be very efficient to work. I am facing problem with session timeout. I have set it to 20 mins on my server but sometimes suddenly i get logged out.
Please help me to understand using session for authentication.
First of all you have to edit web.config and set session timeout attribute.
<configuration>
<system.web>
<sessionState timeout="200"></sessionState>
</system.web>
</configuration>
Another issue is the use of IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["login"] != null && Session["db"] != null)
{
String DB = "";
String AccountID = "";
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
else
{
Response.Redirect("log.aspx");
}
}
I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};
i have two buttons on the page. One button is responsible for text fields validation that are to do with registration and the other with loging in. The problem was when i press one of the buttons it refreshes the page and shows all the invalid fields (i dont want the registration fields to be checked by the RequiredFieldValidator whent the user presses the login button).
so what i did i used the initialization event.. to prevent this from happening...
static bool oneButtonPressed;
protected void Page_Init(object sender, EventArgs e)
{
if (oneButtonPressed)
{
REgisterAge.Visible = false;
RegisterAge2.Enabled = false;
RegisterAge3.Enabled = false;
RegisterPassword.Enabled = false;
RegisterPassword2.Enabled = false;
RegisterEmail.Enabled = false;
RegisterEmail2.Enabled = false;
}
else
{
EntryPasswordRequiredFieldValidator10.Enabled = false;
EntryNameEntryRequiredFieldValidator9.Enabled = false;
}
}
protected void entry_Click(object sender, EventArgs e)
{
oneButtonPressed = true;
}
protected void submitButton_Click(object sender, EventArgs e)
{
oneButtonPressed = false;
}
}
The probelm here is that the bool is always false when the page is posted back and loads again.. i do remember my teacher saying i could either use a ViewState or a static variable/method to preserve my values. Am i being wrong here.. do i have to use the ViewState?
Why don't you assign a validationgroup to each of the fields + the relevant submit button.
Different validation groups will ensure that validation won't fire on the irrelevant form.
<asp:TextBox runat="server" ID="txtName" ValidationGroup="vRegistration"></asp:TextBox>
<asp:LinkButton runat="server" ID="btnSubmit" ValidationGroup="vRegistration"></asp:LinkButton>