2

I am using ASP.Net Identity to manage my users.

I am finding that after calling the following:

AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);

when I check if the user is currently authenticated via HttpContext.Current.User.Identity.IsAuthenticated it returns false.

I managed to get this to return true by doing the following:

FormsAuthentication.SetAuthCookie(model.UserName, false);

Is it possible to set HttpContext.Current.User.Identity.IsAuthenticated to true?

Brendan Green
  • 11,676
  • 5
  • 44
  • 76
  • 1
    At what point are you checking `HttpContext.Current.User.Identity.IsAuthenticated`? If it is immediately after the signin, this will probably be false. Is it still false after loading another page? Also, post your `web.config`, and details of how ASP.NET Identity is being configured. – Brendan Green May 06 '15 at 22:32
  • 1
    Hi, I have solved like `this:HttpContext.GetOwinContext().Authentication.User.Identity` .. Now the question is: Is the correct way ??? – Freddy Castelblanco Macias May 06 '15 at 23:26

1 Answers1

6

You are unnecessarily fighting the system.

AuthenticationManager.SignIn takes an identity parameter that you can use for the remainder of the current request which should be quite short.

var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
Debug.WriteLine(identity.IsAuthenticated); //true 
Debug.WriteLine(this.Request.IsAuthenticated); //false

The purpose of the request at hand is to simply authenticate the user. You shouldn't be doing much more than that, if anything, and then returning the response / doing a redirect.

The reason that this.Request.IsAuthenticated==false even though you just (successfully) authenticated the User is because this value is set by the FormsAuthenticationModule during the initial stages (AuthenticateRequest) of the request pipeline.

The FormsAuthenticationModule will look for the auth-cookie and authenticate (IsAuthenticated=true) according to the information it finds there.

This all happens before you hit the actions in your controller so the request can be short-circuited if it's not authenticated.

So simply authenticating the user in your login action won't change this value because it's too late. All that action does from a request pipeline point of view is attach/revalidate the auth-cookie that will be used by the auth module during the next request.

This again is why we typically redirect right away to have the value updated by the auth module in the next request.

rism
  • 11,932
  • 16
  • 76
  • 116