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.
Related
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.
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
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.
I have created MasterPage.aspx and other Pages.I want if user Click on MainPage anywhere on any link or button without Login it must redirect to my Login.aspx.How can i will create session for this ?.I need idea weather i will code in MasterPage.cs Page_load Method or elsewhere ?.MasterPage.aspx{//code here }Login.aspx{//code here }
Use condition like this on master page:
if (Session["LoggedUserName"] == null && !Request.Path.EndsWith("login.aspx"))
{
Response.Redirect("~/your/path/login.aspx");
}
You can also use: MembershipProvider
This can be see here:
Check Session variable and Redirect to login page before page load
You can easily put your code in Page_load event of MasterPage :
if(Session["Login"] == null)
{
Response.Redirect("/Login.aspx");
}
Update :
If you use the MasterPage for all of pages , automatically clicking on all of anchors cause to checking the session, but if you didn't use MasterPage for all, i think you can do this solution :
First Of All, create a class like this :
public class MyPage : Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if(Session["User"] == null)
{
Response.Redirect("/login.aspx");
}
}
}
After that, when creating pages, inheritance them from MyPage class, for example :
public class Default: MyPage
In login page use this code
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtuser.Text == "User" && txtPassword.Text == "Password")
{
Session["username"] = txtuser.Text;
Response.Redirect("Default.aspx");
}
else
{
lblMessage.Text = "Invalid Username/Password";
}
}
In Master page use this code in load event
if(Session["username"]==null)
Response.Redirect("Login.aspx",false);
Try The following code in MasterPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["UserId"] == null)
{
Response.Redirect("Login.aspx");
}
}
}
Hope it will help you well. Let me Know if get Helped.
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