HttpContext.Current.User.Identity.Name is always string.Empty - asp.net

Hi I use a custom MembershipProvider.
I want to know the current username during an application scenario, but when I try accessing HttpContext.Current.User.Identity.Name it always returns string.Empty.
if (Membership.ValidateUser(tbUsername.Text, tbPassword.Text))
{
FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
bool x = User.Identity.IsAuthenticated; //true
string y = User.Identity.Name; //""
FormsAuthentication.RedirectFromLoginPage(tbUsername.Text, cbRememberMe.Checked);
}
Am I missing something?

FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
bool x = User.Identity.IsAuthenticated; //true
string y = User.Identity.Name; //""
The problem you have is at this point you're only setting the authentication cookie, the IPrincipal that gets created inside the forms authentication module will not happen until there is a new request - so at that point the HttpContext.User is in a weird state. Once the redirect happens then, because it's a new request from the browser the cookie will get read before your page is reached and the correct user object created.
Cookies are only set on the browser after a request is completed.
As an aside RedirectFromLoginPage creates a forms auth cookie anyway, you don't need to do it manually

Please try System.Web.HttpContext.Current.Request.LogonUserIdentity.Name instead of User.Identity.Name. It worked for me.

The value of HttpContext.Current.User.Identity.Name is set by the call to RedirectFromLoginPage. You can get the current user id from HttpContext.Current.User.Identity.Name once you are redirected to a new page. I'm not sure why you would need to access the user name through the User property in this context, couldn't you just use the value contained in tbUsername.Text?

in VS Community 2015 version, if you create a web forms application, it automatically add codes in web.config node to remove FormsAuthentication, try remove below section
<modules>
<remove name="FormsAuthentication"/>
</modules>

As already suggested FormsAuthentication.RedirectFromLoginPage() method, sets the Authentication Cookie automatically.
However in my case, i had nested web applications where i had cleared <httpModules> tag in child application (so that it does not inherit httpModules from its parent application) in the web.config file. Removing the unwanted parent httpModules made everything work again.
its better to check this tag before complicating things :)

If you're looking for the name of the user from the membership provider, try something like this ...
var user = Membership.GetUser( HttpContext.Current.User.Identity.Name );

If you're using URL rewrite or change your URL,it may be cause return Empty null value.You should try change path of your URL from .html to .aspx or none extendtion. this is issue for my case.You try.I hope this useful

Related

User.Identity.IsAuthenticated = field value

In my database table i have a field with usernames.
I want the users that are NOT in that field to be redirected to my default websites.
I dont want the users to be able to copy past the URL for another of my aspx sites only if they are users from my field then its ok
Im looking into User.Identity.IsAuthenticated but how would i combine that with my database field?
If User.Identity.IsAuthenticated = "fieldvalue" then
site1.aspx
Else
Server.transfer("default.aspx)
End If
Should i mabye say something like.
If sqlexecute.hasrows then
Site1.aspx
Else
server.transfere("default.aspx")
End IF
User.Identity.IsAuthenticated is a boolean property and can contain only true/false value. You can just check for truthfulness of IsAuthenticated property and then do the redirection like
if(User.Identity.IsAuthenticated)
{
//redirect to site1.aspx
}
else
{
Server.transfer("default.aspx");
}
EDIT:
You are trying to reinvent the wheel. What you are trying is already built into ASP.NET and known as Forms Authentication
It's very well explained in MSDN. See below MSDN links
Explained: Forms Authentication in ASP.NET 2.0
How to: Implement Simple Forms Authentication

HttpApplication and the current page

As we all know the HttpApplication object holds objects regarding the requested page (HttpRequest) and the page where we are supposed to be redirected (HttpResponse); I need to get the url of the page which requested the page; how could I get it from the HttpApplication ?
You want to check the url referrer header like so:
string MyReferrer = Request.UrlReferrer.ToString();
This value is set by the browser however - so can't exactly be trusted from a security viewpoint.
You need to use the HttpRequest.UrlReferrer property see - http://msdn.microsoft.com/en-us/library/system.web.httprequest.urlreferrer.aspx

Absolute URL Cookieless

Is there some method in asp.net for getting an absolute url with cookieless session?
UPDATE: I need create other new URL. It is not requested URL.
I´m using Response.ApplyAppPathModifier for getting relative URL with cookie session.
Thx in advance,
I tried Request.RawUrl and Request.Url (and its properties in the Immediate window).
None did show the extra attribute the setting (web.config):
<sesionState cookieless="true" />
makes in the url.
Example
http://localhost:2677/WebSite1/(S(3abhbgwjg33aqrt3uat2kh4d))/cookielesssessiondetection.aspx
However if you're after that part, 3abhbgwjg33aqrt3uat2kh4d, you can get it via:
Session.SessionID
Update after the updated question:
I put in my test application a Hyperlink control on the page. In code behind, Page_Load, I added:
HyperLink1.NavigateUrl = Response.ApplyAppPathModifier("About.aspx");
When I run that page then the url to About.aspx gets set with the cookieless session part included.
When I check the source of the rendered html in my browser I see this:
<a id="HyperLink1" href="/WebSite1/(S(3tzgdnmhwxmxqer10d11auuq))/About.aspx">HyperLink</a>
Did you try Request.Url.ToString(). It should work for you.
If you needed was the url of another page on your site then you can proceed like this...
String url = new Uri(Context.Request.Url, ResolveUrl("~/ABC.aspx")).ToString )
We also have something like Request.Url.AbsoluteUri
I hope One of the above should work for you.

Redirect to webapp default document when another page is specified?

IIS6, ASP.NET 2.0, No Forms Authentication
I'm calling Response.Redirect("~/foo.aspx"), but the default document ("Default.aspx") for my site is appearing. To make matters worse, it only happens intermittently. Sometimes the redirect displays the right page.
I've checked session state, and I don't see any values in the web.config (that is, I'm assuming I'm using the 20-minute defaults).
I wish I had more relevant information to share (I'll do my best to answer any questions).
Any ideas? Why isn't it redirecting to the specified page?
EDIT: I've looked deeeeeper into the code and learned more details.
Ok. There's foo.aspx and foo2.aspx (and the default document, Default.aspx). All pages extend from BasePage, which extends Page.
BasePage has a property named ReturnPage:
protected string ReturnPage {
get {
if (Session["ReturnPage"] == null) {
Session["ReturnPage"] = "";
}
return Session["ReturnPage"].ToString();
}
set { Session["ReturnPage"] = value; }
}
Users click on a LinkButton on foo.aspx, and the click event handler ends with two lines of code:
ReturnPage = ResolveUrl("~/foo.aspx");
Response.Redirect(ResolveUrl("~/foo2.aspx"));
The Page_Load of foo2.aspx has problems, and its error handling calls Response.Redirect(ReturnPage).
When I view the response headers of foo2.aspx, the 302 location is string.Empty (that is, there isn't one). That same response header has the same ASP.NET Session ID as the response of foo.aspx.
And remember -- this is intermittent. Sometimes, you can click on that LinkButton and go effortlessly to foo2.aspx, no problem. You can process the click with the exact same data once, and it will fail. You'll navigate from the default document (Default.aspx, where you were sent by the "bug") back to foo.aspx, click again with the same data (the same row in the grid/table -- the same LinkButton, essentially), and you'll be redirected to foo2.aspx without issue.
Placing a value in the session immediately before a Response.Redirect() is risky.
Changing foo.aspx's Response.Redirect() to the following might retain the session value more reliably:
Response.Redirect("~/foo2.aspx", false);
UPDATE: This ended up being fixed only by moving our session state into SQL Server. See related question: Why/when are session writes vulnerable to thread termination?
When you say:
Sometimes the redirect displays the right page.
Does it just happen, and you are not sure if there are certain pages that are affected by the problem? If this is the case, then you probably have a addressing problem. You can use either a relative path or an absolute path rather than an Application-relative path. I would also guess that you are trying to either direct to a page from a subdirectory on your site or to a subdirectory on your site. If you choose to stick with the Application-relative path make sure that are taking the subdirectory into account. (ex: ~/FooPages/Foo.aspx)
Here is a good reference page I just found:
http://nathanaeljones.com/129/types-of-asp-net-paths/
I'm a little confused here. What exactly are you trying to accomplish? You're getting the default document exactly because the 302 is blank. Your "inconsistent" behavior is almost certainly due to the way you are saving data in the Session.
The real issue here is why you're redirecting when foo2.aspx "has problems". What's the problem here? Why redirect? If you really need to redirect, why is the redirect target changed? Make it a static error reporting page and you'll be fine.
Once you redirect and get a new instance of the BasePage from foo2.aspx, won't that ReturnPage property be null again? Then once your page load errors out and tries to redirect it will be accessing a null string. Maybe try throwing that property in the Session
Session.Add("ReturnPage","~/foo.aspx")
instead of
ReturnPage = ResolveUrl("~/foo.aspx");
Ofcourse you would have to modify that error handling in the page load to grab it out of session rather than the property and you may have to rethink how the whole redirect is working in your system if this turns out to be the issue.
EDIT:
To test this idea about the property not getting set, or getting set correctly....(just to test I am not suggesting you should hard code the path in there), change your getter to the example below, then check to see if it works. Hope this helps, I am curious to find out what the problem is if this is not the issue.
get {
if (Session["ReturnPage"] == null) {
Session["ReturnPage"] = "~/foo.aspx";
}
return Session["ReturnPage"].ToString();
}

Programmatically refresh/update HttpContext.User

I'm using FormsAuthentication for an ASP.NET site that has a master page that displays the current logged in user, Page.User.Identity.Name.
They can change their username in their settings, and when the do so, I update their cookie for them so they wont have to sign out/sign back in with a postback.
FormsAuthentication.SignOut();
FormsAuthentication.SetAuthCookie(username, false);
I'm probably being pretty nit-picky, but after they change their username the master page still displays their original username until they reload or load a different page.
Is there any way to programmatically update the current Page.User, so that their new username can be displayed during the same postback?
Though MasterMax's suggestion is what I would do, you can actually update the Page.User via HttpContext.Current.User.
If you know the user's roles (or you aren't using role based authorization), you can take advantage of the System.Security.Principal.GenericPrincipal class:
string newUsername = "New Username";
string[] roles = new string[] {"Role1", "Role2"};
HttpContext.Current.User =
new GenericPrincipal(new GenericIdentity(newUserName), roles);
you could create an instance of your master page class, and make the property that you're setting for the username public, so that you can set that property right after your FormsAuthentication code.

Resources