Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - Site still accessible if not logged in?

I'm converting an existing ASP.Net webapp to MVC / Entity Framework, and I'm an issue with the login functionality.

I have my login page working, that is to say, if they don't enter the correct information, it doesn't redirect to my start page. However, the start page is still accessible if the user enters the URL manually.

I'm fairly new to MVC, and haven't actually created a website with a working login before. Could anybody direct me where to start in order to protect my website from anonymous users?

like image 661
keeehlan Avatar asked Jun 14 '13 15:06

keeehlan


2 Answers

ASP.NET MVC has an attribute simply called Authorize that you can decorate your controller with:

[Authorize]
public class YourController {

}

This will require the user to be authenticated in order to hit any actions on the controller.

You can also specify this at the action level if you require different authentication throughout the controller:

public class YourController {
    public ActionResult OpenToTheWorld() {

    }

    [Authorize]
    public ActionResult GottaLogIn() {

    }
}

One last note... if like me you need to only allow certain groups access to controllers and actions you can do that with the Authorize attribute as well:

[Authorize(Roles = "Administrators, Editor")]

I personally dislike the strings being hardcoded like that so I rolled my own attribute which accepts proper objects:

[MyAuthorize(Roles = new string[] { SiteRoles.Administrator, SiteRoles.Editor })]
like image 109
Justin Helgerson Avatar answered Oct 18 '22 06:10

Justin Helgerson


Have you used the [Authorize] attribute on your Home Page Controller?

I'm guessing not. Otherwise, the user would be automatically redirected to the Login page.

like image 31
Justin Niessner Avatar answered Oct 18 '22 08:10

Justin Niessner