Page view counter

Security in asp.net MVC application

Last post 03-17-2008 3:05 PM by MeetNet. 16 replies.

Sort Posts:

  • Security in asp.net MVC application

    12-10-2007, 10:29 AM
    • Loading...
    • pwelter34
    • Joined on 07-02-2002, 2:04 PM
    • Eden Prairie, MN
    • Posts 12
    • Points 57

    I haven't seen any example of how to do security in an asp.net MVC application.  Will the <location> element in the web.config work to set permissions? Is there some way to do this in the controller?  I've found a post by Fredrik. He indicates using the PrincipalPermission attribute.  This will throw an exception but will not redirect to a login page like asp.net should.  Is there a solution to securing in mvc yet?

    thanks,
    ~ Paul

    ~ Paul
    Filed under:
  • Re: Security in asp.net MVC application

    12-10-2007, 11:19 AM
    • Loading...
    • Mike343
    • Joined on 03-30-2005, 7:59 AM
    • Posts 43
    • Points 125

    You could always make a base controller and have your other controllers you want to secure extend it.

     Example

     public class SecureController : Controller

    {

        public SecureController()

        {

            HttpContext context = HttpContext.Current;

            if (context.User == null || !context.User.Identity.IsAuthenticated)

            {

                // redirect to login.

          } 

        }

    }

     public class MemberController : SecureController

    {

     

    }

  • Re: Security in asp.net MVC application

    12-10-2007, 1:07 PM
    • Loading...
    • DavidHogue
    • Joined on 11-11-2007, 8:20 PM
    • Bend, Oregon
    • Posts 4
    • Points 18

    I haven't tried yet, but I sould assume the <location> and <authorization> tags in the web.config would do it.

    Something like this:
    <location path="SomeController/SomeAction">
       <system.web>
         <authorization>
           <allow users="SomeUser" />
           <deny users="*" />
         </authorization>
       </system.web>
    </location>

    Once I get the CTP installed I'll try it and see what happens.

     

  • Re: Security in asp.net MVC application

    12-10-2007, 1:28 PM
    Answer
    • Loading...
    • robconery
    • Joined on 02-23-2005, 10:16 PM
    • Posts 192
    • Points 846
    • AspNetTeam

    You can indeed lock down your location using this method, but keep in mind we're not using a "file request" scheme here anymore - this is all about RPC (in a sense). Additionally, users of your system might/can/will change the routes at some point, and if/when they do, they can break this FormsAuth security using <location>.

    Your best bet is to use PrinciplePermission on the contoller or method (with many thanks to Phil for this):

    [PrincipalPermission(SecurityAction.Demand,Role="Administrator")]
    [ControllerAction]
    public void Index(){
    ...
    }

    I have a blog post coming on this today.

  • Re: Security in asp.net MVC application

    12-10-2007, 1:38 PM
    • Loading...
    • DavidHogue
    • Joined on 11-11-2007, 8:20 PM
    • Bend, Oregon
    • Posts 4
    • Points 18

    I just tried the <location>, and it kind of works, but I wouldn't use it.  I think the PrincipalPermission attribute (or just using some code like Mike343 suggested) will be the way to go with this.

    I tried it with the default app that is generated that has a Home controller with Index and About actions.  When path="Home" it does block /Home/anything, but you can still see / which is the same as /Home/Index.  Also setting path=Home/About did not stop me from going to /Home/About at all.  Plus the routes can be changed as Rob said.
     

  • Re: Security in asp.net MVC application

    12-10-2007, 1:45 PM
    • Loading...
    • pwelter34
    • Joined on 07-02-2002, 2:04 PM
    • Eden Prairie, MN
    • Posts 12
    • Points 57

    In my experimenting, I couldn't get the<location> element to work.  I like the idea of using PrincipalPermission.  However, that throws an exception.  The controller should redirect to login instead.  It should be easy enough to create a base controller to do this.  Would be really nice if this was built in to the framework though.  Also, throwing an exception doesn't seem very efficient.

    ~ Paul
  • Re: Security in asp.net MVC application

    12-10-2007, 7:34 PM
    • Loading...
    • Angus McDonald
    • Joined on 12-10-2007, 11:18 PM
    • Sydney, Australia
    • Posts 1
    • Points 2

    We allow security permission settings to throw exceptions all the time, and then catch them in our base page and define how to handle a security permission error there (which for a non-logged in user is to re-direct them to the login page). This has the advantage of logging the access attempt as well as cleaning up your code.

    In MVC the idea of having a base controller that you extend makes perfect sense to me. That way you get to write your security handling code once, whilst each individual controller (or even <gasp!> model) can decide what constitutes an unsecured attempt itself and just throw the right error at that point.

    Angus McDonald

    Senior .NET Developer
    Elcom Technology - http://www.elcom.com.au
  • Re: Security in asp.net MVC application

    01-02-2008, 8:49 AM
    • Loading...
    • cromwellryan
    • Joined on 09-23-2003, 12:52 PM
    • Dayton, OH
    • Posts 9
    • Points 12

    There is a post out here which describes setting up the ASP.Net Membership provider with the MVC framework.  It uses the <location/> config elements in the samples, but you can easily use declarative or explicit authorizations.  I'll look at adding a short extension post about those two options.  I would agree that the <location/> config is poorly chosen as it's dependent on the route configuration.

  • Re: Security in asp.net MVC application

    01-02-2008, 10:57 AM
    • Loading...
    • ironside14
    • Joined on 01-02-2008, 3:45 PM
    • Issaquah
    • Posts 56
    • Points 103

    I'm taking the PrinicipalPermission route (no pun intended :) ).

    By creating a base controller class that's security aware, I didn't see the need for a special [ExceptionHandler] attribute for my simple case.

    As an example, a redirecting base controller that blindly redirects security exceptions to the login action of the "security" controller:

    public class MembershipAwareController : Controller
        {
            protected override bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)
            {
                if (exception is System.Reflection.TargetInvocationException &&
                    exception.InnerException is System.Security.SecurityException )
                {
                    // Use TempData as a container for a display message when redirecting the user to login.
                    // I tried setting ViewData but it was always empty by the time the 
                    // Login action is executed. TempData is meant for use on the next request only, so it seems a fitting spot for it.
                    // There is some coupling here as this code assumes the Login controller will do something with TempData (like tell a view to render it).
                    TempData["ErrorMessage"] = "You must login to access this section of the site."; 
                    RedirectToAction("Login", "Security");
                }
                else base.OnError(actionName, methodInfo, exception);
                return false;
            }
        }
     
    Filed under: ,
  • Re: Security in asp.net MVC application

    01-02-2008, 4:52 PM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 815
    • Points 3,797
    • ASPInsiders

    i entered a competition to write the best pun, there were only 10 contestants and mine was clearly the best. I thought mine would win but... no pun in ten did.


  • Re: Security in asp.net MVC application

    02-20-2008, 2:09 PM
    • Loading...
    • JoshuaStroup
    • Joined on 02-14-2008, 5:49 PM
    • Posts 4
    • Points 8

    Does anybody have a way of implementing some type of security inheritance. For example, it would be nice to call .Demand() on just my class and every Controller Action and View is authenticated and authorized if the user authenticates. I would like to use Code Access Security for overriding specific Actions or Views, but I also like the <location> tag functionality that applies system wide. Do I build a large global.asax that handles every exception and reroutes, then I just need to track what exceptions I use throughout the application? Or is there a better way? Maybe I'm missing something here for a solution or not understanding previous posts.

    Respectfully,

    Josh
     

    Filed under:
  • Re: Security in asp.net MVC application

    02-20-2008, 2:17 PM

    In Scott Guthrie's roadmap he showed the first look at what they're calling Filters that he said will be in the next preview. It's essentially PrinciplePermission, but you get to write your own filter and you can have it do whatever you want. You can apply it to the class and then everything inside that class (your controller) is subject to that, or you can apply it to individual methods/actions. That's my take at least. Read his section 5) New Filter Attribute Support for Controllers and Action Methods for more details.

  • Re: Security in asp.net MVC application

    02-21-2008, 10:14 AM
    • Loading...
    • JoshuaStroup
    • Joined on 02-14-2008, 5:49 PM
    • Posts 4
    • Points 8

    Good to know. Thank you Sliderhouserules I'm looking forward to that. Also I want to thank you Angus for the response to my email in which he stated and I'll paraphrase:

    --------------------------------------------

    You can simply create base functions in your controller that check user security permissions for example:

    • isSiteAdmin()
    • isCustomer()
    • isShopUser()
    • isCustomerAdmin()

    Then create a logic trap at beginning of methods that need to be secured. (He used VB I'll translate to C# as I'm more familiar with the syntax)

     
    if ( isAdmin() ) { 
    
       Throw New System.Security.SecurityException("Access Denied. User is unable to view this page.");
    
    } 
    
    RenderView("Index");
     

    -------------------------------------------- 

    Alternatively you could also (I took this from Maarten Balliauw) http://blog.maartenballiauw.be/post/2007/12/ASPNET-MVC-framework---Security.aspx

     

    try {
        PrincipalPermission permission = new PrincipalPermission(User.Identity.Name, "Administrators", true);
        permission.Demand();
    } catch (SecurityException secEx) {
        // Handle the Exception here...
        // Redirect to Login page, for example.
    }
     

     

    But I personally like Angus's method better. Anyway this is just me trying to give back because of the great answers I receive from people willing to take time out and help our professions. 

  • Re: Security in asp.net MVC application

    03-12-2008, 1:21 PM
    • Loading...
    • MeetNet
    • Joined on 03-12-2008, 1:13 PM
    • Posts 13
    • Points 10

    The latest MVC release does not have an override bool for OnError. What is the right way to catch things (pun intended) now? 

     

    ironside14:

    ...snip... 

    public class MembershipAwareController : Controller
        {
            protected override bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)
            {
                if (exception is System.Reflection.TargetInvocationException &&
                    exception.InnerException is System.Security.SecurityException )
           ...snip...
     
     
    Filed under:
  • Re: Security in asp.net MVC application

    03-12-2008, 1:36 PM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 815
    • Points 3,797
    • ASPInsiders

     override OnActionExecuted, if no error occured then Exception will be null, if you handle the exception (by rendering an error view) set ExceptionHandled to true.

Page 1 of 2 (17 items) 1 2 Next >