Samantha J T Star
Samantha J T Star

Reputation: 32848

How can I make every controller except the account controller in my WebAPI application require a user to be authenticated

I realize that I can decorate each controller with [Authorize].

However is there a way that I can do this globally so that it's the default and then have the Account controller set as anonymous only ?

Upvotes: 1

Views: 490

Answers (4)

Pedro Drewanz
Pedro Drewanz

Reputation: 1292

You can add the AuthorizeAttribute globally by changing your FilterConfig to add it to all requests:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    //Other filters
    filters.Add(new AuthorizeAttribute());
}

After that you can add the [OverrideAuthorization] attribute to your controller.

If you have any AuthenticationFilter set globally it won't be reseted. If you want to reset both you also need to use the [OverrideAuthentication] attribute.

Upvotes: 0

Apply the filter globally like this.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Existing code
        config.Filters.Add(new System.Web.Http.AuthorizeAttribute());
    }
}

Then, apply [AllowAnonymous] on the AccountController or specific action methods.

[AllowAnonymous]
public class AccountController : WebApiController {}

Upvotes: 1

devqon
devqon

Reputation: 13997

Use a basecontroller, from which each controller inherits. Then set the [Authorize] attribute on the base controller.

Upvotes: 2

Dan
Dan

Reputation: 1480

Create a BaseController which all other controllers inherit from. Have this class then inherit from Controller, like so

SomeController : BaseController

Then in BaseController

BaseController : Controller

Add an authorize attribute to the base controller. All controllers inheriting from BaseController will now require authorization. Controllers which don't, wont. So, your account controller will only inherit from Controller, not BaseController as you don't want this authorized.

There are other advantages of having a base controller. You can override OnAction executed to log application usage for instance.

I would create a second base controller called BaseUnsecuredController which your account controller can inherit from which won't have an authorize attrubute. Then have an abstract base controller class which contains the implementations of common actions you wish to share between the base controllers, like logging and error handling.

Hope this helps.

Upvotes: 4

Related Questions