I am using MVC 4.
First page it is navigating to http://localhost:61700/
where it has username and password to proceed further...
Now, I can also access direct url by typing http://localhost:61700/AccountInfo
and other pages as well without login to the app.
How can I restrict this, if user not logged in and typed direct URL, it needs to go to the error page
HomeController.cs
using System.Web.Mvc;
namespace myWebSite.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AccountStatus()
{
return View();
}
...................
You can apply Authorize attribute to make it restrict from unauthorized users. Also you can apply role and add user if you want to.
[Authorize]
public class PrivateResourcesController : ApiController
{
public IHttpActionResult Get()
{
return Ok(DateTime.Now);
}
}
[Authorize(Roles ="Admin",Users ="foo@mail.com")]
public class PrivateResourcesController : ApiController
{
public IHttpActionResult Get()
{
return Ok(DateTime.Now);
}
}
Just a simple idea:
Create a controller, say SecureController
inherited from Controller
and have only this method
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (Session["LoggedIn"] == 1) { base.OnActionExecuting(filterContext); } else { filterContext.Result = RedirectToAction("Index", "Login"); } }
Other than the LoginController
, inherit all other controllers from SecureController
Have Index (or name it whatever you like) method do the login. Set Session["LoggedIn"]
to 1 after successful login.
Thats all you need. Of course this is just a simple thought provoking idea to put you on the right path. This will allow you to redirect to any page if user is not logged in. No form authentication configuration required. This gives you total control on how to authenticate a user.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.