Access control in a ASP.MVC application
I use the following code for controlling access in a ASP.MVC application (this a piece of a controller):
public ActionResult MakeEditable(int id)
{
// controlling part
if (!User.Identity.IsAuthenticated)
{
return RedirectToAction("Login", "User", new {
callback = Url.Action("MakeEditable", "Article", new { id = id })
});
}
// action's body
}
It is very inconvenient for writing the controlling part for each action, so I'm looking the way to avoid it. If it was Nemerle I could use a attribute level macros, but for C#, I think, the best approach is PostSharp. What are the other ways to provide this functional开发者_开发问答ity you could advise?
There are several options for authorization in ASP.NET MVC. The way you are doing is indeed very inconvenient, but there is a better way! You DO have attribute macros in C# :)
[Authorize]
public ActionResult DoSomething(int someParam)
{
//Do stuff here.
Return View();
}
The [Authorize] tag can be placed directly above any action on a controller or even above the controller class itself to make the entire controller accessible only to authenticated users.
[Authorize]
public class HomeController : Controller
{
//Actions and stuff
}
If you are using the membership and role provider you can even include a role filter in the attribute.
[Authorize(Roles="trader")]
public ActionResult SomeAction(int someParam)
{
//stuff...
}
It is also possible to apply authorization to entire URL routes. Similar to the way you would apply directory level authorization in traditional ASP.NET Web Forms. Just add something like this to your web.config:
<location path="Admin">
<system.web>
<authorization>
<deny users="?"/>
<allow roles="SiteAdmin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
This tells UrlAuthorizationModule (which is registered for all ASP.NET applications by default) that for the URL ~/Admin and URLs matching ~/Admin/*, it should do the following:
• Deny access for unauthenticated visitors ()
• Allow access for authenticated visitors in the SiteAdmin role ()
• Deny access to all other visitors ()
精彩评论