Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Membership.GetUser().UserName; (.net 4, mvc 3)

i log users into .net using straightforward .net authentication:

if ( Membership.ValidateUser( user, passwd ) )

works fine. hot on the heels of that, i try to get the user name:

Membership.GetUser().UserName

sometimes this will return an invalid object. sometimes not. i cannot seem to detect a pattern as to which is which.

for example, a user logs in with a valid role in the system as 'root'/'password'. the ValidateUser() call succeeds, but Membership.GetUser().UserName returns an invalid object. 2 seconds later, do the same exact thing again, and both the validate and the GetUser() succeed.

any ideas?


.. edit 1 .. here's how i use the username:

Roles.GetRolesForUser( Membership.GetUser().UserName ); 

when i swap in System.Environment.UserName, the roles list comes back empty.

if i leave it as is and i set the auth cookie using 'true' as my second argument, it works fine.

FormsAuthentication.SetAuthCookie( user, true );

if i use HttpContext.Current.User.Identity.Name, the roles list is fine with the auth cookie set to true or false.

now, i understand the issue about performance. this is important to me. but i also need to ensure the application functions correctly.

like image 991
horace Avatar asked Jan 17 '26 20:01

horace


2 Answers

Why can't you use

HttpContext.Current.User.Identity.Name

?

like image 106
AndrewC Avatar answered Jan 21 '26 09:01

AndrewC


Membership.ValidateUser() returns true or false whether the user is valid or not, but it does not sign them in.

Membership.ValidateUser Method

Verifies that the supplied user name and password are valid.

Try this instead:

bool createPersistentCookie = true; // remember me?

if (Membership.ValidateUser(user, passwd)) {
    FormsAuthentication.SetAuthCookie(user, createPersistentCookie);
    if (FormsAuthentication.GetAuthCookie(user, createPersistentCookie) == null)
        throw new SecurityException("Authentication persistence failed");

    Membership.GetUser().UserName; // should have a value now
}
else
{
    // invalid login
}
like image 22
hunter Avatar answered Jan 21 '26 07:01

hunter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!