views:

181

answers:

3

In the authentication control I have the following line to mark a user as authenticated in the system (after checking out the password):

FormsAuth.SignIn(userName, rememberMe);

and if I redirect, which is the standard behvaior, everything is ok. But if I show a view right away, the usual ways to check whether a user is authenticated:

Page.User.Identity.IsAuthenticated
Request.IsAuthenticated

don't work. They say the user is not authenticate. How can I make the authentication effective immediately or is there another way to check that would allow me to find out when the user just logged in?

A: 

On your Controllers, you should be able to use the following to check if they're authenticated.

User.Identity.IsAuthenticated;

I would check to make sure that your AccountController is properly saving the Principal object as you move from page to page.

mbmccormick
+3  A: 

FormsAuth.SignIn is a function which is generated when you create a new ASP.NET MVC project from Visual Studio.

That function simply calls FormsAuthentication.SetAuthCookie, which according to the docs, sets the authentication cookie in the response.

This explains why it works if you redirect (because the client will play back the cookie in the subsequent request), but not right after the call.

Redirecting is the right/conventional way to do this, but if you absolutely insist on checking authentication before a redirect, then you could create an IsAuthenticated flag in session state and refer to that when checking.

DSO
A: 

In addition to using the FormsAuth.Signin or FormsAuthentication.SetAuthCookie, you can also set the User.Identity manually in your sign-in control when the sign-in code executes. As written above, the reason is because the FOrmsAuth.SignIn simply sets the authentication cookie to be picked up next time in the Request_OnAuthenticate event. (Which simply decodes the cookie and sets the HttpContext.User property)

Eric Falsken