How can I create a "security aware" action link that detects if a user is authorized to click (invoke) the action?
Hide link if user is not allowed to use that action...
Depending from
- web.config (authorization) and
- [Authorize] attributes on actions
PS
I guess it is bad practice to mix those 2 in MVC?
This is some code poached from the MvcSitemap project and modified for my own use. If I remember correctly this code has been modified for MVC2 and some of the functions might have to be back ported to MVC1.
Its not bad practices at all to mix MVC and FormsAuthentication together, MVC's default authentication methods are build around the existing Asp.net security infrastructure.
Code to determine if user has permissions:
Html Helpers
Warning: This won't work in MVC 5 because the call to FindAction() never returns an action descriptor
I tried to find the issue and couldn't and ended up programming a work around. :(
The Area part is a bit more complicated than just adding some overloads. The UseNamespaceFallback hack doesn't work because you will instantiate the wrong when you have identically named controllers in different Areas.
You need to have a way to get the correct namespace for the Area
otherwise this
Will go wrong.
Currently I have the links like this in the view
Inside
I will get the namespace for the area or the default namespace when area is empty.
You need to setup the default namespace in your route in globalasax for example like this (default ns "ActionLinkTest.Controllers"):
use it to create the controller based on the type name:
in global.asax define the areas
jfar's code worked for me for the most part, but I had to make some modifications for MVC4. This is the only method that had to change: