HttpContext.Current.User.Identity.IsAuthenticated is always false

3

I am trying to recover the currently logged-in user on my system, but for some reason the IsAuthenticated property always returns a false :

I'm using this class to set the user to the context and to retrieve the logged-in user, which is in a class library project:

namespace Helper
{
public static class SessionHelper
{
    public static bool ExistUserInSession()
    {
        return HttpContext.Current.User.Identity.IsAuthenticated;
    }

    public static void DestroyUserSession()
    {
        FormsAuthentication.SignOut();
    }
    public static int GetUser()
    {
        int user_id = 0;
        if (HttpContext.Current.User != null && HttpContext.Current.User.Identity is FormsIdentity)
        {
            FormsAuthenticationTicket ticket = ((FormsIdentity)HttpContext.Current.User.Identity).Ticket;
            if (ticket != null)
            {
                user_id = Convert.ToInt32(ticket.UserData);
            }
        }
        return user_id;
    }
    public static void AddUserToSession(string id)
    {
        bool persist = true;
        var cookie = FormsAuthentication.GetAuthCookie("usuario", persist);

        cookie.Name = FormsAuthentication.FormsCookieName;
        cookie.Expires = DateTime.Now.AddMonths(3);

        var ticket = FormsAuthentication.Decrypt(cookie.Value);
        var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, id);

        cookie.Value = FormsAuthentication.Encrypt(newTicket);
        HttpContext.Current.Response.Cookies.Add(cookie);
    }
}
}

After a validation of user and password vs my database I use the AddUserToSession method to set the user to the session, if I clean those lines I can see how the cookie and ticket are generated correctly .

This is the part of the Action where I send to call the mentioned method:

if (ModelState.IsValid)
    {
        _usuarioViewModel.Email = model.Email;
        _usuarioViewModel.Password = model.Password;

        var usuarioDomain = Mapper.Map<UsuarioViewModel, Usuario>(_usuarioViewModel);
        UsuarioDto usuarioDtoDomain = _userRepository.Login(usuarioDomain);

    //Si la autenticacion no fue exitosa la capa correspondiente regresa un CustomException
        if (usuarioDtoDomain != null)
        {
            SessionHelper.AddUserToSession(usuarioDtoDomain.UsuarioId.ToString());

            return View("~/views/home/index.cshtml");
        }

Well, until here everything is fine it logs and apparently sets the user Id to the context, the issue occurs when I ask for the authenticated user, from the view to show the username:

 @if (SessionHelper.ExistUserInSession())
 {
 <div class="row">
     <div class="col-xs-12 text-center well">
         Bienvenido, <b>@FrontUser.Get().Email</b> [<a href="~/home/salir">Finalizar sesión</a>]
     </div>
 </div>
  }  

As you can see, SessionHelper is a static class but for some reason when calling the function:

public static bool ExistUserInSession()
{
   return HttpContext.Current.User.Identity.IsAuthenticated;
}

This always returns false.

This is the corresponding section of the web.config.

<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
<authentication mode="Forms">
  <forms name="prueba" cookieless="UseCookies" protection="All" />

</authentication> 
</system.web>

If someone with more experience can see something wrong, I will be very grateful if you inform me or offer a tip to find the source of my problem.

    
asked by jose luis garcia 13.04.2016 в 22:04
source

5 answers

1

To solve the problem you should create the authentication cookie for the provided user. To do this before recovering the cookie in the AddUserToSession method you must do FormsAuthentication.SetAuthCookie (id, persist);

public static void AddUserToSession(string id)
{
    bool persist = true;
    // generar cookie de autenticación
    FormsAuthentication.SetAuthCookie(id, persist);
    var cookie = FormsAuthentication.GetAuthCookie(id, persist);

    cookie.Name = FormsAuthentication.FormsCookieName;
    cookie.Expires = DateTime.Now.AddMonths(3);

    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, id);

    cookie.Value = FormsAuthentication.Encrypt(newTicket);
    HttpContext.Current.Response.Cookies.Add(cookie);
}
    
answered by 10.09.2016 в 02:35
1

I have had your same problem and I have solved it by editing Web.config adding the following lines:

<system.web>
    <authentication mode="Forms">
      <forms name="prueba" cookieless="UseCookies" protection="All" />
    </authentication>
</system.web>

For what I read, you have already done it but it may be useful for other people.

Greetings.

    
answered by 21.09.2017 в 19:10
0

If we validate the article

Forms Authentication Configuration and Advanced Topics (C #)

You can see that he uses

HttpCookie authCookie = FormsAuthentication.GetAuthCookie(UserName.Text, RememberMe.Checked);

that is, it does not define a fixed "user" text but uses the name of the user that is entered in the login

    
answered by 13.04.2016 в 22:47
0

Define loginUrl in the web.config :

assuming your page is login.aspx :

<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
<authentication mode="Forms">
  <forms name="prueba" cookieless="UseCookies" protection="All" />
  <forms loginUrl="~/home/login.aspx" defaultUrl="~/home/index.cshtml" />
</authentication> 
</system.web>
    
answered by 13.04.2016 в 22:43
0

I found the problem and it is due to a configuration in the web.config that is automatically added when occupying the class "FormsAuthentication". Simply comment the line or delete this one.

The code that you described above, added to the comments and adjustments of the others, works correctly.

    
answered by 22.09.2017 в 14:24