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");
}
}
Related
So i want to prevent session tampering in my site and i implemented this in global.asax. What im doing is im generating a hash key using the GenerateHashKey function. which basically uses the browser version,userhost address etc to create a hash key. This hash key im attaching to ASP.NET_SessionId cookie. Now this works perfectly in local environment. but as soon as i host it to prod server, the "Invalid" exception is thrown the first time and then it works fine. why is this happening
I used this article
http://www.codeproject.com/Articles/859579/Hack-proof-your-asp-net-applications-from-Session
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
if (Request.Cookies["ASP.NET_SessionId"] != null && Request.Cookies["ASP.NET_SessionId"].Value != null)
{
string newSessionID = Request.Cookies["ASP.NET_SessionId"].Value;
//Check the valid length of your Generated Session ID
if (newSessionID.Length <= 24)
{
//Log the attack details here
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30);
Response.Cookies["ASP.NET_SessionId"].Value = null;
throw new HttpException("Empty");
}
//Genrate Hash key for this User,Browser and machine and match with the Entered NewSessionID
if (GenerateHashKey() != newSessionID.Substring(24))
{
//Log the attack details here
Response.Cookies["TriedTohack"].Value = "True";
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30);
Response.Cookies["ASP.NET_SessionId"].Value = null;
throw new HttpException("Invalid:"+newSessionID);
}
//Use the default one so application will work as usual//ASP.NET_SessionId
Request.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Substring(0, 24);
}
}
catch(Exception Ex)
{
if (Ex.Message == "Invalid")
{
Response.Redirect(string.Format("~/PraiseError.aspx?Message={0}", Uri.EscapeDataString(Ex.Message)));
}
else
{
Response.Redirect("~/Home.aspx");
}
}
}
protected void Application_EndRequest(object sender, EventArgs e)
{
string gn = GenerateHashKey();
try
{
//Pass the custom Session ID to the browser.
if (Response.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Replace(gn, "") + gn;
}
else
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + gn;
}
}
catch
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + gn;
}
}
private string GenerateHashKey()
{
StringBuilder myStr = new StringBuilder();
myStr.Append(Request.Browser.Browser);
myStr.Append(Request.Browser.Platform);
myStr.Append(Request.Browser.MajorVersion);
myStr.Append(Request.Browser.MinorVersion);
myStr.Append(Request.UserHostAddress);
//myStr.Append(Request.LogonUserIdentity.User.Value);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hashdata = sha.ComputeHash(Encoding.UTF8.GetBytes(myStr.ToString()));
return Convert.ToBase64String(hashdata);
}
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;
}
}
what i am tryin to do is
i have common login page with 4 users each has different roles
and i have a Singel master pages where i have different contorls.....how to provide authentication to the own page with the contorls assigned to them..regarding on thier role they should be directed to the given page....
user 1 manager he needs only some controls on the page so when he logins the master page should contain only the controls assgned to him
applys the same for all users
can any one help me......planing ,i dont know where to start....
Try This in Button Click
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUserName.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
{
Response.Redirect("~//Administration/Manager/WorkManagement.aspx");
}
else if (TypeUser.ToString() == "HR")
{
Response.Redirect("~//Administration/Hr/CalculateAndGeneratePayslips.aspx");
}
else if (TypeUser.ToString() == "Employee")
{
Response.Redirect("~//Administration/CallingAgent/TodaysWork.aspx");
}
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
There is simple way for this approach below are the steps you can follow
Keep one default Master Page // ("MasterPage.master")
Add as many master pages according to requirement // "manager.master/Admin.master"
Add the Pages to the default Master page
Add class file in app_code where u can map dynamic masterpage
Add this class in App_Code
public class DynamicPage : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
string masterfile = getMasterPageFromDatabase();
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
base.OnPreInit(e);
}
private string getMasterPageFromDatabase()
{
// check the conditions "manager.master/Admin.master"
return "Admin.master";
}
}
when coming to .cs file for default.aspx.cs it would be "System.Web.UI.Page" replace that with DynamicPage
public partial class _Default : **System.Web.UI.Page**
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
finally it comes like
public partial class _Default : **DynamicPage**
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
rest will happen automatically mapped
hope this helps !!!
I have a list of strings, which are generated on a imagebutton_click method. I want to be able to use this list in another webpage.
How ever im not quite sure how to go about posting it between the two pages.
I have the following code below:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
RadGrid rg = RadGrid1;
//Get selected rows
GridItemCollection gdc = (GridItemCollection)rg.SelectedItems;
foreach (GridItem gi in gdc)
{
if (gi is GridDataItem)
{
GridDataItem gdi = (GridDataItem)gi;
if (!string.IsNullOrEmpty(gdi["Email"].Text))
{
string client = gdi["Email"].Text;
//Creating a List of Clients to be Emailed
emailList.Add(email);
}
}
//Enable the Prepare Email Page
PageView2.Selected = true;
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if (emailList.Count != 0)
{
for (int i = 0; i < emailList.Count; i++)
{
_to = emailList[i].ToString() + ";";
}
}
else
{
_to = emailList[1].ToString();
}
//Processing Client Email
string _from = sec.GetCurrentUserEmail("test");
string _cc = "";
string _subject = SubjectTB.Text;
string _body = EmailEditor.Content;
string _tempTo = sec.GetCurrentUserEmail("temp");
string _msg = sec.SendMail(_tempTo, _cc, _from, _subject, _body, "");
if (_msg == "success")
{
//Thank the user and record mail was delivered sucessfully
TestPanel.Visible = true;
}
}
How do I get the values of emailList to be passed through to ImageButton2_click(object sender, ImageClickEventArgs e). Currently it just passes through a null value. I gather I need to use HTML forms to do the request. Thanks.
I'm guessing that emailList is a private variable? Wouldn't you be able to add that to the LoadControlState and SaveControlState so that it'll be available for ImageButton2_Click later?
Here is an example: http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadcontrolstate%28v=vs.80%29.aspx
Another possibility is hidden field, that might be the simplist way, but not as secure.
You can get a good idea about state management in ASP.Net here. For your case if button1 and button2 are in the same aspx page, Viewstate would be a good idea. If they are in diferent pages then use Session state management.
Heey Stackoverflow,
I have an question im started to learn asp.net language csharp and i have the following login code my question is how to begin or where can i learn to write down the session cookie and than i can get back to the other page to read this cookie out again for the username and password that did match ty very much
public partial class Administratie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string cnnString = ConfigurationManager.ConnectionStrings["Stefan"].ConnectionString;
using (SqlConnection con = new SqlConnection(cnnString))
using (SqlCommand cmd = new SqlCommand("select [Username],[Password] from Admin where [Username] = #Username and [Password] = #Password", con))
{
string Username = (textUsername.Text.Length > 0) ? textUsername.Text : null;
string Password = (TextPassword.Text.Length > 0) ? TextPassword.Text : null;
cmd.Parameters.Add("#Username", System.Data.SqlDbType.VarChar).Value = textUsername.Text;
cmd.Parameters.Add("#Password", System.Data.SqlDbType.VarChar).Value = TextPassword.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
if (Page.IsValid)
{
// Login Succeed
// Response.Redirect("Admin.aspx");
}
}
}
}
catch (Exception) { }
// Login Failed
Response.Write("Wrong Username ");
}
}
Try look here:
Create and retrieve Cookie data (C#)
Read a Cookie:
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
lblWelcome.Text = "<b>Unknown Customer</b>";
}
else
{
lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
lblWelcome.Text += "Welcome, " + cookie["Name"];
}
Set a Cookie
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}
cookie["Name"] = txtName.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
If you want to store data in a Session just set it:
Session["username"]=username;
and read:
string username=Session["username"];
You can use session to store username and password. If you want to use remember me option you can save the username and password in cookies.
Please check the links for using session and cookies