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?
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 })]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With