Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does FormsAuthentication.SetAuthCookie() Require a Redirect?

After checking a user's credentials and confirming they are good, I'm using FormsAuthentication.SetAuthCookie("Username", false); to authenticate the user.

In the masterpage I then use Page.User.Identity.IsAuthenticated to make sure we're dealing with a logged in user and not a guest.

The problem lies in first setting the auth cookie. When I set the auth cookie, immediately afterwards I run a method that uses Page.User.Identity.IsAuthenticated to change the welcome message from a generic "Welcome, guest!" message to a more personal "Welcome, username!" message. This does not work until I go to another page, so I know the login process has worked, but it seems I cannot access the information I need until a refresh or a redirect happens.

Do I need to redirect the user after setting the auth cookie in order use Page.User.Identity.IsAuthenticated to change the message?

like image 657
Sgt Beardy Avatar asked Feb 03 '23 06:02

Sgt Beardy


1 Answers

I have seen this before so I know the answer is yes. (As in, yes you do need to redirect the user to correctly use Page.User.Identity.IsAuthenticated)

What I imagine is the cause is because IsAuthenticated evaluates the current request, and when the current request first came in it was recorded as not authenticated.

What you will need to do is apply whatever logic you have in said method without the check for IsAuthenicated (make it assume true).

Now I don't know the details of your method as to suggest how to re-factor it to cope with this, but you could split out the "Do Stuff" part into a separate function which you could then call directly from you login function to bypass the authentication check.


EDIT: To back up my assumption you can read this page.

The interesting part:

The forms-authentication ticket supplies forms-authentication information to the next request made by the browser.

like image 93
musefan Avatar answered Feb 11 '23 10:02

musefan