ASP.NET prevent accessing the homepage before and after logout - c#

I have a login page and a homepage. It's not possible to access homepage without login but after i login and click logout at the homepage. Users are able to access homepage from browser's address row. How can prevent this ? Here is my implementation
Login Click Method at AdminPanelLogin.aspx.cs:
protected void adminLoginButton_Click(object sender, EventArgs e)
{
String adminName = adminNameText.Text;
String password = adminPwdText.Text;
AdminPanelLoginProcess aplp = new AdminPanelLoginProcess();
if (aplp.adminLogin(adminName, password))
{
Session["AdminAuthentication"] = aplp.Admn.AdminID;
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Write("<script>alert('Login failed !');</script>");
}
}
Logout Click Method at AdminPanel.aspx.cs
protected void adminPanelLogoutLink_Click(object sender, EventArgs e)
{
Session["AdminAuthentication"] = null;
Session.Abandon();
Response.Redirect("AdminPanelLogin.aspx");
}
AdminPanel.aspx.cs Page Load Method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AdminAuthentication"] == null)
{
Response.Redirect("AdminPanelLogin.aspx");
}
else
{
if (!IsPostBack)
{
showProducts();
showModels();
showShoes();
}
else
{
if (Session["AdminAuthentication"] == null)
{
Response.Redirect("AdminPanelLogin.aspx");
}
}
}
}

By default, the back button does not reload the page but get it from cache. Try to disable cache in AdminPanel.aspx as
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now);
or use any other method from http://www.codeproject.com/Tips/135121/Browser-back-button-issue-after-logout.aspx

Related

asp.net login system via c#

i have four pages login.aspx , main.aspx, Sub.aspx, final.aspx. Final page needs authentication to be accessed which i have provided using forms authentication.Logging in through login.aspx it redirects to final.aspx because defaultUrl is set to final.aspx .currently i am going from main.aspx to sub.aspx to final.aspx which redirects to login.aspx after logging in final.aspx. what i want is if i start from login.aspx it should redirect to main.aspx to sub.aspx to final.aspx, jumping from sub.aspx to final.aspx should not redirects to login as already logged in.
But directly accessing the final.aspx should always redirects to login.aspx
login code
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1 .Text =="abc" && TextBox2 .Text =="xyz")
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
}
else
{
Response.Write("w");
}
}
final page code
protected void Page_Load(object sender, EventArgs e)
{
if (User .Identity .IsAuthenticated )
{
Response.Write("welcome");
}
else
{
FormsAuthentication.RedirectToLoginPage();
}
}
web config
<authentication mode ="Forms">
<forms name ="abc" loginUrl ="login.aspx" defaultUrl="final.aspx"/>
</authentication>
I would do it like that:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
Response.Write("welcome");
}
else
{
Response.Redirect("/login.aspx");
}
}
I probably would first show a message "Not authorised. Please log in" with a link to the login page. instead of redirecting.
Hope this helps.
I popose you a better use Session for this case to handle the URL redirecting and authentication.
Try this
To use Session, you need to inherit "Page" in your class :
public class Class1 : Page
Sub page
aspx:
<a id="gotofinal" href="#" OnClick="GoToFinal_Click">Go To Final</a>
aspx.cs:
protected void GoToFinal_Click(object sender, EventArgs e)
{
Session["GoToFinal"] = "Y";
Response.Redirect("final.aspx");
}
Final Page :
protected void Page_Load(object sender, EventArgs e) {
if ((string)Session[IsAuthenticated] == "Y")
{
Session["GoToFinal"] = "";
Response.Write("welcome");
}
else
{
Response.Redirect("login.aspx");
}
}
Login page :
protected void Page_Load(object sender, EventArgs e) {
Session["IsAuthenticated"] = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "abc" && TextBox2.Text == "xyz")
{
Session["IsAuthenticated"] = "Y";
if (!String.IsNullOrEmpty((string)Session["GoToFinal"]) && (string)Session["GoToFinal"] == "Y")
{
Response.Redirect("final.aspx");
}
else
{
Response.Redirect("main.aspx");
}
}
else
{
Response.Write("Login Failed");
}
}
You also need to make logout button in final.aspx to clear the Session[IsAuthenticated]
Session["IsAuthenticated"] = "";
Hope it helps.

How to get the login value of the id and pass that to the next page

So i have a login page that is using the membership class.. what i am trying to do is get the username that they pass in and once they are authorised immediatly i would like the username to be passed into a stored proc to show the relevant data for that user.. At the moment, when the user has logged in they are taken to the next page, but i want the info for that user to be ready straight away.. im new to coding and not sure how to do it... What i have so far...
LOGIN PAGE...
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
// This is an unauthorized, authenticated request...
Response.Redirect("~/UnauthorizedAccess.aspx");
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
//Validating against the user store
if (System.Web.Security.Membership.ValidateUser(UserName.Text, Password.Text))
{
FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
}
//if we get here then the credentials were invalid
InvalidCredentialsMessage.Visible = true;
}
}
login page works fine but not sure how to divert to the supplier page and automatically pass the username in to my stored procedure (The stored procedure is working fine in sql, but i dont know how to get it to pass param.)
Here is the page i want to divert to and automatically show my stored procedure..
public partial class Update : System.Web.UI.Page
{
private int VendorId { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
public void RefreshGrid(int VendorId)
{
try
{
//get list of records from vendorId
BizManager biz = new BizManager();
DataTable dt = new DataTable();
dt = biz.GetMaterialAndDesc(VendorId);
SupplierView.DataSource = dt.DefaultView;
SupplierView.DataBind();
}
catch (Exception ex)
{
ErrMsg = App.App.HandleError(MethodBase.GetCurrentMethod(), ex, "Application Failed adding products to the list");
}
}
private string ErrMsg
{
get { return ErrMsgUpdate.Text; }
set { ErrMsgUpdate.Text = value; }
}
}
I think you want
User.Identity.Name
That gives you the Username
Or if you are in a Class somewher use
System.Web.HttpContext.Current.User.Identity.Name

Ensure page is accessed from a specific link

Say if I have link1.aspx and link2.aspx. Within link1.aspx, I redirect the user to link2.aspx.
What is the most efficient way of checking that link2.aspx is only accessed via link1.aspx?
For example, something like:
link2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if page is not accessed via link1.aspx
{
Response.Redirect("~/portal.aspx");
}
}
}
I could use a query string but are there any other ways?
You can use UrlReferrer. However, it is not a secure way of detecting where the user comes from.
For example,
if (string.Equals(Request.UrlReferrer.AbsoluteUri,
"YOUR_REFERRER_URL",
StringComparison.InvariantCultureIgnoreCase))
{
}
If it is redirecting between pages inside your application, I would like to suggest to use SessionState which is more secure and robust than UrlReferrer.
link1.aspx.cs
private bool IsValidUrl
{
set { Session["IsValidUrl"] = true; }
}
protected void Button1_Click(object sender, EventArgs e)
{
IsValidUrl = true;
Response.Redirect("link2.aspx");
}
link2.aspx.cs
private bool IsValidUrl
{
get
{
if (Session["IsValidUrl"] != null)
return Convert.ToBoolean(Session["IsValidUrl"]);
return false;
}
set { Session["IsValidUrl"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsValidUrl)
{
// user comes from valid url.
// .... Do somthing
// Reset session state value
IsValidUrl = false;
}
}
You could use the Request.UrlReferrer property to check what page the user is coming from.

Inherit from MasterPage

In a Web Form project, I using MasterPage for user Role and Other-Pages inherit from MasterPage.
I try to use this codes into the Load function in MasterPage :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string MyPage = System.IO.Path.GetFileName(Request.Path);
SqlDataReader RolePageDr = BLL.Users.RolesPage(MyPage);
while (RolePageDr.Read())
{
string Rolepage = RolePageDr["Roles"].ToString();
if (Page.User.IsInRole(Rolepage) != true)
{
Response.Redirect("~/MsgPage.aspx");
}
else
Response.Redirect(MyPage);
}
}
}
But the problem is that when the user redirected to the Other-pages (For Example: AdminPage), this admin page inherited from MasterPage and this Load function run again and a again.
It will run again and again; that is the nature of stateless programming. But what you can do is use session to store it, and then only reload it when session isn't there, as in:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string role;
var sessionValue = Session["Roles"];
if (sessionValue != null)
role = sessionValue.ToString();
else
{
string MyPage = System.IO.Path.GetFileName(Request.Path);
SqlDataReader RolePageDr = BLL.Users.RolesPage(MyPage);
while (RolePageDr.Read())
{
role = RolePageDr["Roles"].ToString();
Session["Roles"] = role;
}
}
if (Page.User.IsInRole(Rolepage) != true)
{
Response.Redirect("~/MsgPage.aspx");
}
else
Response.Redirect(MyPage);
}
}
Session keeps the value and prevents constant checking of the database, but when it expires, the page reloads it and stores it in session again.

How to load web user control dynamically?

This is really important question. this makes me crazy in 4 hours :( i can load UCAddX.ascx but if i click "Search in X" button not load UCSearchX user control. There are 3 button also there are 3 web user control. i want to load these 3 web user controls after clickEvents. But below method not working.How to load web user control dynamically? Click By Click (Like Tab control)
public partial class MyPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ViewState["controlType"] = "AddX";
if (!IsPostBack)
{
AddUserControl();
}
else
{
AddUserControl();
}
}
protected void btnAddX_Click(object sender, DirectEventArgs e)
{
ViewState["controlType"] = "AddX";
if (!IsPostBack)
AddUserControl();
else
AddUserControl();
}
protected void btnSearchX_Click(object sender, DirectEventArgs e)
{
ViewState["controlType"] = "SearchX";
if (!IsPostBack)
AddUserControl();
else
AddUserControl();
}
protected void btnUpdateX_Click(object sender, DirectEventArgs e)
{
}
void AddUserControl()
{
// plhContent1.Controls.Clear();
if (ViewState["controlType"] != null)
{
if (ViewState["controlType"].ToString() == "AddX")
{
UCAddX uc = (UCAddX)Page.LoadControl("~/Pages/EN/MyUserControls/UCAddX.ascx");
uc.ID = "ucAddX";
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
plhContent1.Controls.Add(uc);
}
else if (ViewState["controlType"].ToString() == "SearchX")
{
UCSearchX uc = (UCSearchX)Page.LoadControl("~/Pages/EN/MyUserControls/UCSearchX.ascx");
uc.ID = "ucSearchX";
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
plhContent1.Controls.Add(uc);
}
}
}
}
Use the code below to load usercontrol dynamically
var control = LoadControl(filePath) as ControlType;
then you can subscribe to events and add to control placeholder.
Hope this helps
try something like this,
//to load the control
protected void Page_Init(object sender, EventArgs e)
{
ViewState["controlType"] = "AddSector";
//you don't need to check the if condiontion, cause you load every time the controls
AddUserControl();
}
when you need to get values from the control after postback you should get it on
protected void Page_PreRender(object sender, EventsArgs args) {
//your placeholder that contains data
}
User controls when loaded dynamically need to be loaded on every Page_Load so their view state is maintained. So you need something like:
public string CurrentControlToLoad
{
get
{
if(ViewState["controlType"] == null)
return "";
return (string)ViewState["controlType"];
}
set
{
ViewState["controlType"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(CurrentControlToLoad != "")
LoadControl(CurrentControlToLoad);
}
protected void btnAddSector_Click(object sender, DirectEventArgs e)
{
CurrentControlToLoad = "AddSector";
LoadControl(CurrentControlToLoad);
}

Categories