Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect users, who or not logged in to login page, in C# MVC 4.5 if they try to access other site pages via URL

I have one website, where I want users to be redirected to "Login" page if they are not signed in. The users may try to access the webpages by posting url. I want to do it in C# MVC 4.5

Here I dont want the action "[Authorize]" to be available unless signed in. It is index action to view index page.

  //Login Controller
  [AllowAnonymous]
  public ActionResult Index()
  {
      return View();
  }
  [HttpPost]
   public ActionResult Index(FormCollection frm)
    {
        ....//other code
    }

 [Authorize]
 public ActionResult Index()
    {
        List<DTO> obj = objConfigurator.GetDataList();
        return View(obj);
    }


    public ActionResult Edit(int Id)
    {
        DTO obj = objC.GetListById(Id);
        return View(obj);
    }
like image 912
Pranav Avatar asked Mar 03 '15 06:03

Pranav


1 Answers

Use the [Authorize] attribute on your controller.

[Authorize] 
public class YourController: Controller
{
 . . .
    [AllowAnonymous]
    public ActionResult Register()
    {
    }

    [AllowAnonymous]
    public ActionResult LogIn()
    {
    }
. . .
} 

Also, you have to add your login page in the web.config -

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Login" timeout="2880" />
    </authentication>
</system.web>

You have another, even better option, to register AuthorizeAttribute as global filter in the global.asax file.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)

{
    ....
    filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}

This way, you only have to apply the [AllowAnonymous] to actions tha you want to be visited by anonimous users.

like image 136
vortex Avatar answered Jan 03 '23 17:01

vortex