Accessing data stored in cookies?

3

At login, I store user information logged into a cookie (name, password, etc ...)

How do I access this cookie and retrieve information from it?

For example, I want the name of the logged in user to appear in the upper bar, my logic would have to find the name already stored in the file and throw it in @Viewbag determined in controller , is correct this way of thinking? And what is the most aesthetic and correct way of doing this?

Here is the example of when you are authenticating:

[HttpPost]
    public ActionResult Login(Login form, string retornarurl)
    {
        var usr = db.Usuario.FirstOrDefault(u => u.nome == form.nome);

        if (usr == null || !usr.CheckPassword(form.passwordHash))
            ModelState.AddModelError("nome", "Usuário ou senha estão incorretos ou não existe");

        if (!ModelState.IsValid)
            return View(form);

        FormsAuthentication.SetAuthCookie(usr.nome, true);

        return RedirectToAction("Index", "Admin" );

    }
    
asked by anonymous 23.10.2015 / 19:02

1 answer

4

You use the old way, which was used in Web Forms. It can be done this way:

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

string cookiePath = ticket.CookiePath;
DateTime expiration = ticket.Expiration;
bool expired = ticket.Expired;
bool isPersistent = ticket.IsPersistent;
DateTime issueDate = ticket.IssueDate;
string name = ticket.Name;
string userData = ticket.UserData;
string version = ticket.Version;

I recommend you take a look at ASP.NET Identity , which performs more interesting user management and registration cycles, login and logging of external logins.

    
23.10.2015 / 21:16