Authentication in asp.net - asp.net

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache );
Response.Cache.SetAllowResponseInBrowserHistory(false);
}
This code i have used to authenticate the website,its working but only when the user copies the url and paste it in a new window,but opening in the new window leads to the next page without any login credentials.

For authentication:
In page_Load Events
if (session(user_id) != null) {
response.redirect("the_page_which_you_want_to_go.aspx");
} else {
response.redirect("Login.aspx");
}

Related

User.Identity.Name = "" but user is authenticated. possible?

protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
if (!IsPostBack)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
}
the user loged in and he is authenticated, but when I check for his name I get ""
I try to get the user name using a jquery ajax, and I return the data to the ajax
update:
a look at my immediate window (while in a break point) when a user named moria is logedin
**User.Identity**
{System.Web.Security.FormsIdentity}
[System.Web.Security.FormsIdentity]: {System.Web.Security.FormsIdentity}
AuthenticationType: "Forms"
**IsAuthenticated: true**
**Name: ""**
**Membership.GetUser()**
**null**
**Membership.GetUser("moria")**
{moria}
Comment: null
CreationDate: {23/02/2016 01:10:08}
Email: "orders.gca#gmail.com"
IsApproved: true
IsLockedOut: false
IsOnline: false
LastActivityDate: {24/02/2016 03:21:08}
LastLockoutDate: {01/01/1754 02:00:00}
LastLoginDate: {24/02/2016 03:21:08}
LastPasswordChangedDate: {23/02/2016 01:10:08}
PasswordQuestion: "1"
ProviderName: "MySqlMembershipProvider"
ProviderUserKey: {ff589472-e852-4049-8803-6d22740414ee}
UserName: "moria"
Taking from ADreNaLiNe-DJ's answer and adding in the ability to redirect back to the calling page, you would add this to the Global.asax file:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var loginUrl = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Login", "Account") ?? "";
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains(loginUrl))
{
Response.Redirect(loginUrl + "?ReturnUrl=" + Request.Url.AbsoluteUri);
}
}
Hope that helps.
First of all, you should check authentication earlier in the pipeline.
Add this code in your Global.asax.cs:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains("login.aspx"))
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
}
You check authentication for all pages/requests in 1 unique place.
So when you are in the Page_Load, you are sure to be logged in and authenticated.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}

web service is unable to return back to default page

I have asmx web service hosted on IIS and its purpose is to authenticate logined user.
when I run my code using visual studio and debug service is successfully called and authenticate user from DB but it is unable to transfer control back to my code that has default page.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
Response.Redirect("Default.aspx");
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
Session["Uri"] = Request.UrlReferrer;
}
this.hdnLoginStatus.InnerHtml = "";
if (!Page.IsPostBack)
{
new DAS().AuthenticateRequest();
if (HttpContext.Current.Items["LoginStatus"] == null)
return;
var key = (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"];
string msg = (string)GetGlobalResourceObject("Message", key.ToString()) ?? "";
this.ShowMessage(msg, MessageType.Warning);
this.hdnLoginStatus.InnerHtml = "SignedOutForcefully";
}
}
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?key=" + (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"]);
}

select master page at run time for a specific page

I have an asp page employeeHome.aspx and I have two master pages adminMasterPage.master for Admin login and userMasterPage.master for normal user login as I have 2 types of user login one as Admin and other normal user. And I want to set adminMasterPage.master as a master page for employeeHome.aspx in case of normal user login (just for this page).
How can I do this?
Put your code to change the master page in Page_PreInit event.
protected void Page_PreInit(object sender, EventArgs e)
{
this.MasterPageFile = "MasterPage.master";
}
Put the code at employeeHome.aspx page
protected void Page_PreInit(object sender, EventArgs e)
{
if (Session["empCode"] != null)
{
if (Session["empCode"].ToString() != "0")
{
this.MasterPageFile = Server.MapPath("adminMasterPage.master");
}
}
}
You can change that by having the required master page file specified in the PreInit event, which is a part of the page life cycle..
protected void Page_PreInit(object sender, EventArgs e)
{
this.MasterPageFile = "adminMasterPage.master"; //For Admin
//this.MasterPageFile = "userMasterPage.master"; - For Normal User
}
This worked this way and here what I did as suggest by #Iswanto San and made changes in the path.
protected void Page_PreInit(object sender, EventArgs e)
{
if (Session["IsEmporAdm"].ToString() == "0")
{
this.MasterPageFile = "~/StyleLibrary\\layout\\AdminMaster.Master";
}
else
{
this.MasterPageFile = "~/StyleLibrary\\layout\\UserMaster.Master";
}
}

ASP Membership Current user not taking the right value

i am using an ASP control Login and i want to redirect the user logged in depending on its role. But it seems like The User take the previous value of the last logged in user. seems problem of refresh the current user or something like this
Code of my webform1.aspx.cs:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox1.Text = Context.User.Identity.Name.ToString();
if (Context.User.IsInRole("admin"))
{
Response.Redirect("~/admin.aspx");
}
else if (User.IsInRole("user"))
{
Response.Redirect("~/user.aspx");
}
}
Inside LoggedIn event of Login control, principal object hasn't been attached to the current HttpContext yet.
Therefore, you cannot use Context.User inside LoggedIn event.
protected void Login1_LoggedIn(object sender, EventArgs e)
{
var roles = Roles.GetRolesForUser(Login1.Username);
if (roles.Contains("admin"))
{
Response.Redirect("~/admin.aspx");
}
else if (User.IsInRole("user"))
{
Response.Redirect("~/user.aspx");
}
}

get username after login

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.

Resources