views:

337

answers:

2

i am extending the default asp.net mvc example.. i am using asp.net membership provider that comes with it . .

the issue is that if i access one of my url's directly without logging on it shows the full page with "Log On" link at the top.

I want it to obvious redirect to the login page, if anyone accesses any of the specific action urls and they are not logged in.

do i need to put specific logic in every action of every controller to check for "is Logged in?"\

any best practices here.

+7  A: 

You need to decorate your controller actions with "[Authorize]" and set up the correct login page in the web config, so whenever an action that is decorated gets called, it checks if the user is logged on and redirects to the proper login page if not.

EDIT: Here's an example on how to configure it:

in the web.config... add:

 <authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn.aspx" timeout="30"/>
 </authentication>

This will indicate the page where unauthenticated users will be redirected to when they hit a controller decorated with [Authorize()]

in your controller (this can be at the action level or at the controller level, here's shown at the action level)

public class HistoryController : Controller
{
...
[Authorize]
public ActionResult MyActionThatNeedAuthentication()
{
   ...
}
...

}
Jaime
You can place the decoration at the top of the class as well so that you can lock down an entire controller in one go.
griegs
can you give me an example here.. if i have [Authorize] where does the code go if the user is not authorized?
ooo
If the user is not authorized the are redirected to ~/Account/LogOn.aspx. If they successfully log in they will be taken back to the page they originally requested.
ctford
A: 

You can also define the authorized users or roles in the attribute as comma separated lists

[Authorize(Users = "User1,User2")]
public ActionResult ActionName()
{
return View();
}

or

[Authorize(Roles = "Role1,Role2")]
public ActionResult ActionName()
{
return View();
}
Buzzrick