ASP.NET MVC 2 Authorization Problem

I use my own membership provider. Everything works great. However, in my web.config file, I have “block users”, so the whole site is blocked.

This works great. The user is redirected to the login page.

Now I have several controllers / actions that I want to allow anonymous access. About page, password reset, etc.

The only way to find out how to do this is to unlock the entire site, put the [Authorize] attributes on each controller and delete them for the controller / action that I want anonymously.

It seems to me the opposite. I prefer to block everything by default and unlock anonymous.

Is there any way around this?

Thank!

+3
source share
2 answers

, AuthorizeAttribute. - , AuthorizeAttribute, . ( ) , - , . , , " ". /, - . , , , .

, .

[OverridableAuthorize]
public abstract class ProtectedController : Controller
{
}

public class MostlyProtectedController : ProtectedController
{
    public ActionResult ProtectedAction()
    {
    }

    [AnonymousEnabled]
    public ActionResult PublicAction()
    {
    }
}

[AnonymousEnabled]
public class ExplicitlyPublicController : ProtectedController
{
    // inherits additional behaviors, but anonymous is enabled by attribute
}

public class PublicByOmissionController : Controller
{
    // doesn't inherit and is thus public -- assuming whole site is open
}

public class AnonymousEnabledAttribute : Attribute
{
}

public class OverridableAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization( AuthorizationContext context )
    {
          context.HttpContext.Items["ActionDescriptor"] = context.ActionDescriptor;
          base.OnAuthorize( context );
    }

    public override bool AuthorizeCore( HttpContextBase context )
    {
         var actionDescriptor = context.Items["ActionDescriptor"] as ActionDescriptor;
         if (actionDescriptor == null)
         {
             throw InvalidOperationException( "ActionDescriptor missing from context" );
         }
         var attribute = actionDescriptor
                             .GetCustomAttributes( typeof(AnonymousEnabledAttribute,true)
                             .FirstOrDefault();
         if (attribute == null)
         {
             return base.AuthorizeCore( context );
         }
         return true;
    }
}
+3

web.config , :

<configuration>
    <system.web>
        ...
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
    ...
    <location path="MyArea/MyController">
        <system.web>
            <authorization>
                <allow users="*" />
            </authorization>
        </system.web>
    </location>
    ...
</configuration>
+1

Source: https://habr.com/ru/post/1784159/


All Articles