Programmatically refresh/update HttpContext.User - asp.net

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.

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

User.Identity.Name no longer retains username of current logged in user after creating new user in ASP.NET?

I am pretty new to asp.net membership classes. Please forgivwe me for asking such a fundamental question. I did a brief search but have not found the answer and I'm running out of time.
I am making use of the LoginName, LogIn and CreateUSerWizard controls.
Everything works fine except when I create a new user. The Login Name immediately changes to the show the name of the new user I created. I store the User.Identity.Name in a Session("user") at log in so I thought I could change the contents of User.Identity.Name by setting it the value of the Session variable in the ActivateStep event of the CompleteWizard Step but User.Identity.Name is read only.
How do I change the content of User.Identity.Name or change the content of LogInName after Creating a new User?
If you're using the CreateUserWizard to create a new user, you'll need to set the LoginCreatedUser property to false.

How not cache an ASP.NET user control?

I'm using OutputCache in my page that has a user control, but I don't want to cache this specific user control because it's related to a user login (if I access the page, I see the page as if I were authenticated with another user).
How can I do that?
Personally I use the VaryByCustom attribute to give logged in and logged out users different cached page views:
<%# OutputCache VaryByCustom="IsLoggedIn" Duration="30" VaryByParam="*" %>
then in global.asax you put
public override string GetVaryByCustomString(HttpContext context,
string arg)
{
if (arg == "IsLoggedIn")
{
if (context.Request.IsAuthenticated)
{
return "Logged in: " + context.User.Identity.Name;
}
else
{
return "Not Logged In";
}
}
else
{
return base.GetVaryByCustomString(context, arg);
}
}
I am just going to throw this out there. How about the substitution control?
http://msdn.microsoft.com/en-us/library/ms228212.aspx
According to msdn website:
The Substitution control lets you
create areas on the page that can be
updated dynamically and then
integrated into a cached page. ...
The Substitution control offers a
simplified solution to partial page
caching for pages where the majority
of the content is cached. You can
output-cache the entire page, and then
use Substitution controls to specify
the parts of the page that are exempt
from caching.
I have never used the substituion control personally, but I just happened to look it up the other day, and it sounded like it can somehow inject updated content into an otherwise cached page output.
You can cache a page and you can cache a user control, but you can't cache a page except for a user control. When the user control runs the entire page has to run. You have to make the output cache for the page recognise the different users.
You can use VaryByHeader="Cookie" to cache the page for each set of cookies if the user identity is stored in a cookie. You can use VaryByCustom="SomeString" and implement a check for SomeString to do your own check for user identity in the GetVaryByCustomString method in Global.asax.
You can create a cache filter : http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx
Check inside this filter if the user is logged or not.

asp.net membership - approval from admin

I am using the asp.net mvc sample app and have expanded it a bit. I use the asp.net membership for login and registration for users.
I now want to change it so when people register, instead of instantly being able to login, it goes to some state where an administrator has to approve it. Once this approval happens, then they can log in.
Is there anything built into asp.net membership stuff that will help me to do this or do I have to code it up from scratch using my own implementation?
I have a few ideas and I don't think this is rocket science but I don't want to reinvent the wheel as I want to ship this as soon as possible.
The MembershipUser class has an IsApproved property. You may set it to false when creating a new user and then set it to true when the admin approves the user.
You have to call Membershi.UpdateUser(user) method after setting the property.
Here's some code to build a collection of un-approved users that can be used as the datasource of a data control like a GridView, DataList, or Repeater:
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUserCollection unapprovedUsers = new MembershipUserCollection();
foreach (MembershipUser u in users)
{
if (!u.IsApproved)
unapprovedUsers.Add(u);
}
The MembershipUser class has an IsApproved property, and during user creation you can use one of the overloads on the Membership.CreateUser function which allows that flag to be set. Unfortunately there's no easy way to say "Show me all users who are not yet validated".

HttpContext.Current.User.Identity.Name is always string.Empty

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

Resources