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

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();
}
}

Related

session timeout not working properly in global.asax

In my asp.net project I have an event in global.asax as session end which fires when the session is timeout and in this event, I am calling one stored procedure that updates logout time and flag in the table. But when the user is log in and after some work user close browser and on next day when he tries to log in at first attempt message shows that user is already login but when he tried to log in again he is able to log in.
please help its production issue.
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
objUserRole.SchemaName =
(string)CBase.TripleDESDecode(Application["SchemaName"].ToString(),
CBase.EncryptionKey);
if (Session["UserId"] != null)
objUserRole.UserId = (string)Session["UserId"];
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
}
void Application_Error(object sender, EventArgs e)
{
Exception ex = this.Server.GetLastError().GetBaseException();
}
public HttpSessionState GetSession()
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Session;
}
else
{
return this.Session;
}
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
string userid = Convert.ToString(GetSession()["UserId"]);
objUserRole.UserId = (string)CBase.TripleDESDecode(userid,
CBase.EncryptionKey);
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
// objUserRole.funcUpdateLoggedIn();
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
finally
{
Session.Abandon();
Session.Clear();
}
}
</script>

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"]);
}

HOW TO ADD membershipCreateStatus

This is the code behind of button named "Create". How can i add automatically "membershipCreateStatus" through the condition if. I try to add it manualy and i get an erroe message: "The name 'membershipCreateStatus' does not exist in the current context"
protected void btnAddUser_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
membershipCreateStatus
}
}
}
}
you need to add
using System.Web.Security;
protected void btnAddUser_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
MembershipCreateStatus createStatus;
MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus);
}
}

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.

Authentication in 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");
}

Resources