"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Authentication and Authorization in ASP.NET Web API

by Mike Wasson

You’ve created a web API, but now you want to control access to it. In this series of articles, we’ll look at some options for securing a web API from unauthorized users. This series will cover both authentication and authorization.

The first article in the series gives a general overview of authentication and authorization in ASP.NET Web API. Other topics describe common authentication scenarios for Web API.

[!NOTE] Thanks to the people who reviewed this series and provided valuable feedback: Rick Anderson, Levi Broderick, Barry Dorrans, Tom Dykstra, Hongmei Ge, David Matson, Daniel Roth, Tim Teebken.

Authentication

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

When the host authenticates the user, it creates a principal, which is an IPrincipal object that represents the security context under which code is running. The host attaches the principal to the current thread by setting Thread.CurrentPrincipal. The principal contains an associated Identity object that contains information about the user. If the user is authenticated, the Identity.IsAuthenticated property returns true. For anonymous requests, IsAuthenticated returns false. For more information about principals, see Role-Based Security.

HTTP Message Handlers for Authentication

Instead of using the host for authentication, you can put authentication logic into an HTTP message handler. In that case, the message handler examines the HTTP request and sets the principal.

When should you use message handlers for authentication? Here are some tradeoffs:

Generally, if you don’t need to support self-hosting, an HTTP module is a better option. If you need to support self-hosting, consider a message handler.

Setting the Principal

If your application performs any custom authentication logic, you must set the principal on two places:

The following code shows how to set the principal:

[!code-csharpMain]

   1:  private void SetPrincipal(IPrincipal principal)
   2:  {
   3:      Thread.CurrentPrincipal = principal;
   4:      if (HttpContext.Current != null)
   5:      {
   6:          HttpContext.Current.User = principal;
   7:      }
   8:  }

For web-hosting, you must set the principal in both places; otherwise the security context may become inconsistent. For self-hosting, however, HttpContext.Current is null. To ensure your code is host-agnostic, therefore, check for null before assigning to HttpContext.Current, as shown.

Authorization

Authorization happens later in the pipeline, closer to the controller. That lets you make more granular choices when you grant access to resources.

### Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

You can apply the filter globally, at the controller level, or at the level of inidivual actions.

Globally: To restrict access for every Web API controller, add the AuthorizeAttribute filter to the global filter list:

[!code-csharpMain]

   1:  public static void Register(HttpConfiguration config)
   2:  {
   3:      config.Filters.Add(new AuthorizeAttribute());
   4:  }

Controller: To restrict access for a specific controller, add the filter as an attribute to the controller:

[!code-csharpMain]

   1:  // Require authorization for all actions on the controller.
   2:  [Authorize]
   3:  public class ValuesController : ApiController
   4:  {
   5:      public HttpResponseMessage Get(int id) { ... }
   6:      public HttpResponseMessage Post() { ... }
   7:  }

Action: To restrict access for specific actions, add the attribute to the action method:

[!code-csharpMain]

   1:  public class ValuesController : ApiController
   2:  {
   3:      public HttpResponseMessage Get() { ... }
   4:   
   5:      // Require authorization for a specific action.
   6:      [Authorize]
   7:      public HttpResponseMessage Post() { ... }
   8:  }

Alternatively, you can restrict the controller and then allow anonymous access to specific actions, by using the [AllowAnonymous] attribute. In the following example, the Post method is restricted, but the Get method allows anonymous access.

[!code-csharpMain]

   1:  [Authorize]
   2:  public class ValuesController : ApiController
   3:  {
   4:      [AllowAnonymous]
   5:      public HttpResponseMessage Get() { ... }
   6:   
   7:      public HttpResponseMessage Post() { ... }
   8:  }

In the previous examples, the filter allows any authenticated user to access the restricted methods; only anonymous users are kept out. You can also limit access to specific users or to users in specific roles:

[!code-csharpMain]

   1:  // Restrict by user:
   2:  [Authorize(Users="Alice,Bob")]
   3:  public class ValuesController : ApiController
   4:  {
   5:  }
   6:     
   7:  // Restrict by role:
   8:  [Authorize(Roles="Administrators")]
   9:  public class ValuesController : ApiController
  10:  {
  11:  }

[!NOTE] The AuthorizeAttribute filter for Web API controllers is located in the System.Web.Http namespace. There is a similar filter for MVC controllers in the System.Web.Mvc namespace, which is not compatible with Web API controllers.

Custom Authorization Filters

To write a custom authorization filter, derive from one of these types:

The following diagram shows the class hierarchy for the AuthorizeAttribute class.

Authorization Inside a Controller Action

In some cases, you might allow a request to proceed, but change the behavior based on the principal. For example, the information that you return might change depending on the user’s role. Within a controller method, you can get the current principle from the ApiController.User property.

[!code-csharpMain]

   1:  public HttpResponseMessage Get()
   2:  {
   3:      if (User.IsInRole("Administrators"))
   4:      {
   5:          // ...
   6:      }
   7:  }





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>