Pergunta

I'm implementing a login to my website by simply authenticating the user and recording it's information in cookies. In order to protect pages that require registered users, what I'm doing is to call a method that reads the cookie and tries to authenticate the user again, so if the cookie is not expired and the user and pass inside of it is found in the db, the session goes on.

Since I'm calling this method in every action in the controller, I'm kind of unsure if what I'm doing is right or not, so my question is that is there a better way to secure the access to the controller without having to rewrite the same code over and over ?

Example of what I've done:

public ActionResult Act1 () {
     if (CheckCookie() == true)
        return View();
     else 
        return RedirectToAction("Login","Home");
}

public ActionResult Act2 () {
     if (CheckCookie() == true)
        return View();
     else 
        return RedirectToAction("Login","Home");
}

As you can see the same kind of code is repeated in each action in the way I'm implementing the login.

Foi útil?

Solução

You will want to have a look at http://www.asp.net/identity as this is a great starting point for performing authentication within an ASP.NET website. It includes links to resources on how to create new project templates using OAuth, OpenId or FormsAuthentication.

You are trying to write your own kind of Forms Authentication which is not necessary. In ASP.NET MVC if you implement FormsAuthentication using ASP.NET Identity or other classes you can have those classes securely write the cookie and retrieve it for you at runtime (securely). With Forms Authentication in place on your ASP.NET MVC Website you can then decorate your controllers or action methods with decorators such as [Authorize] or [AllowAnonymous] which controls access to those resources (securely).

Please have a look at that reference and as was suggested in comments, create a new Template in MVC and have a look at the sample code the template creates for you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top