CodeLikeBeaker
CodeLikeBeaker

Reputation: 21312

FormsAuthentication Membership.GetUser() Null

I am using Forms Authentication and have the basic logon page and default page.

When I am on the logon page, and call the SignOn this works just great. However, when I am still on the Logon page the Membership.GetUser() returns null. When I redirect to my default page, the Membership.GetUser() returns my user information.

Is there any way I get get this method to return my user while still on the logon page. I have read all over google that other have similar issues where it will only work once you redirect.

Let me know if you need further information.

Here is a simple code snippet of what I am using to verify that the information is being set:

bool authenticated = User.Identity.IsAuthenticated;
            string username = User.Identity.Name;

            MembershipUser user = Membership.GetUser();

I put this code on both the logon page and the default page in the code behind and only the default page has values and shows that it is authenticated after the authentication process executes.

Upvotes: 9

Views: 13417

Answers (6)

jmoreno
jmoreno

Reputation: 13571

I had a similar problem (it was all pages on the site) and it was caused by an error in the AspNetSqlMembershipProvider connection string, which SHOULD have been different in different environments but wasn't, so it worked locally but not when deployed to the server.

Upvotes: 0

Simon Hawes
Simon Hawes

Reputation: 111

I had this issue and found it was due to having multiple membership providers, so instead of

Membership.GetUser()

you can try

Membership.Providers["MyMembershipProvider"].GetUser()

or more specifically

Membership.Providers["MyMembershipProvider"].GetUser(LoginCtrl.UserName, false)

Upvotes: 0

Etienne
Etienne

Reputation: 1106

I had a similar issue and the problem turned out to be that I was missing authentication method = form in the web config .

<system.web>
    <authentication mode="Forms"/>
    ....

Don't forget that one (I was migrating an old legacy site to aspnet)

Upvotes: 2

Clay Smith
Clay Smith

Reputation: 1079

I was in this same situation, here is what worked for me on MVC 4 .NET 4.5.

Membership.GetUser(HttpContext.Current.User.Identity.Name)

Upvotes: 2

David
David

Reputation: 131

Something else to try is the following code:

 MembershipUser user = Membership.GetUser(username);
 GenericIdentity identity = new GenericIdentity(user.UserName);
 RolePrincipal principal = new RolePrincipal(identity);
 System.Threading.Thread.CurrentPrincipal = principal;
 HttpContext.Current.User = principal;

Upvotes: 13

Chris Simpson
Chris Simpson

Reputation: 8000

This might be because you allow anonymous users on your login page. Therefore the browser doesn't bother sending any more information to this page than is necessary.

Upvotes: 11

Related Questions