Accessing data stored in cookies?

Asked

Viewed 117 times

3

In login, I store user information logged in to a cookie (name, password, etc...)

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

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

Follow the example of when you authenticate:

[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" );

    }
  • You are using an authentication provider such as Membership or Identity?

  • I don’t think so. I created a repository for authentication myself, which will later be done through a custom form.

  • You can put a part of his code in your question?

  • In vdd it is in the same controller...

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, that performs more interesting user management and the cycles of registration, login and registration of external logins.

  • Hm... interesting. But in this mode there, I would have to create a repository ?

  • Why you need to create a repository? Reimplemente Principal. It’s much more elegant.

  • And you would have some practical example of what authentication would look like in this way?

  • 1

    I never had to reimplement because I currently use ASP.NET Identity (I used ASP.NET Membership), but suddenly I can do this as an exercise. I recommend this article to you.

  • 1

    I understand, I’ve been doing a study in Identity, but because it is Codefirst and create different tables, it is more complicated for me because it is already an existing project and have a database already created. I’ll take a look at the recommended article.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.