سؤال

I have an mvc4 intranet website that I am working on that has a web front-end that only a few AD groups will have access to, but I am also using the web API functionality of mvc4 and I need that open to all users, even anonymous ones. I have tried using the Web.config, but that blocks all users who are not in one of the groups.

How would I go about securing the front-end while keeping the API open?

Update:

I just thought, I would like to avoid tagging each method with an attribute like [Authorize]

هل كانت مفيدة؟

المحلول

Figured it out.

I simply applied a filter that checked the namespace of each controller. Since all my API controllers are in HSServer.Controllers.Api and all the web controllers are in HSServer.Controllers.Web this code in my FilterConfig.cs worked like a charm.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new FrontendAuthorize());
        filters.Add(new HandleErrorAttribute());
    }
}

public class FrontendAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        try
        {
            if (!filterContext.Controller.GetType().Namespace.StartsWith("HSServer.Controllers.Api"))
                base.OnAuthorization(filterContext);
        }
        catch (NullReferenceException)
        {
            base.OnAuthorization(filterContext);
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top