Windows authentication with web api

Проверка подлинности и авторизация веб-API ASP.NET Authentication and Authorization in ASP.NET Web API

Вы создали веб-API, но теперь хотите управлять доступом к нему. You’ve created a web API, but now you want to control access to it. В этой серии статей мы рассмотрим некоторые варианты защиты веб-API от неавторизованных пользователей. 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.

  • Проверка подлинности — это знание удостоверения пользователя. Authentication is knowing the identity of the user. Например, Алиса входит в систему с именем пользователя и паролем, а сервер использует пароль для проверки подлинности Алисы. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice.
  • Авторизация позволяет решить, разрешено ли пользователю выполнять действие. Authorization is deciding whether a user is allowed to perform an action. Например, Алиса имеет разрешение на получение ресурса, но не на создание ресурса. For example, Alice has permission to get a resource but not create a resource.

В первой статье серии приводятся общие сведения о проверке подлинности и авторизации в веб-API ASP.NET. The first article in the series gives a general overview of authentication and authorization in ASP.NET Web API. В других разделах описываются распространенные сценарии проверки подлинности для веб-API. Other topics describe common authentication scenarios for Web API.

Благодаря людям, которые проверили эту серию, вы указали ценные отзывы: Рик Андерсон (, Бродерикк, Барри Доррансом, Tom Dykstra), Хонгмеи GE, Дэвид Матсон, Даниэль Roth), Тим Тибкен. 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

Веб-API предполагает, что проверка подлинности выполняется на узле. Web API assumes that authentication happens in the host. Для веб-размещения узел является IIS, который использует модули HTTP для проверки подлинности. For web-hosting, the host is IIS, which uses HTTP modules for authentication. Вы можете настроить проект для использования любого из модулей проверки подлинности, встроенных в IIS или ASP.NET, или написать собственный модуль HTTP для выполнения пользовательской проверки подлинности. 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.

Когда узел выполняет проверку подлинности пользователя, он создает участника, который представляет собой объект IPrincipal , представляющий контекст безопасности, в котором выполняется код. 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. Узел присоединяет участника к текущему потоку, устанавливая Thread. CurrentPrincipal. The host attaches the principal to the current thread by setting Thread.CurrentPrincipal. Участник содержит связанный объект Identity , содержащий сведения о пользователе. The principal contains an associated Identity object that contains information about the user. Если пользователь прошел проверку подлинности, свойство Identity. IsTrue возвращает значение true. If the user is authenticated, the Identity.IsAuthenticated property returns true. Для анонимных запросов функция проверки подлинности возвращает значение false. For anonymous requests, IsAuthenticated returns false. Дополнительные сведения об участниках см. в разделе безопасность на основе ролей. For more information about principals, see Role-Based Security.

Обработчики сообщений HTTP для проверки подлинности HTTP Message Handlers for Authentication

Вместо использования узла для проверки подлинности можно поместить логику проверки подлинности в обработчик сообщений HTTP. Instead of using the host for authentication, you can put authentication logic into an HTTP message handler. В этом случае обработчик сообщений проверяет HTTP-запрос и задает участника. 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:

  • HTTP-модуль видит все запросы, которые проходят через конвейер ASP.NET. An HTTP module sees all requests that go through the ASP.NET pipeline. Обработчик сообщений видит только те запросы, которые перенаправляются в веб-API. A message handler only sees requests that are routed to Web API.
  • Можно задать обработчики сообщений для каждого маршрута, что позволяет применить схему проверки подлинности к конкретному маршруту. You can set per-route message handlers, which lets you apply an authentication scheme to a specific route.
  • Модули HTTP относятся к службам IIS. HTTP modules are specific to IIS. Обработчики сообщений не зависят от узла, поэтому их можно использовать как в веб-размещении, так и в автономном размещении. Message handlers are host-agnostic, so they can be used with both web-hosting and self-hosting.
  • Модули HTTP участвуют в ведении журналов IIS, аудита и т. д. HTTP modules participate in IIS logging, auditing, and so on.
  • Модули HTTP выполняются ранее в конвейере. HTTP modules run earlier in the pipeline. При обработке проверки подлинности в обработчике сообщений участник не получает значение Set до запуска обработчика. If you handle authentication in a message handler, the principal does not get set until the handler runs. Более того, участник возвращается к предыдущему участнику, когда ответ покидает обработчик сообщений. Moreover, the principal reverts back to the previous principal when the response leaves the message handler.
Читайте также:  Рекомендуемый компьютер для windows 10

Как правило, если поддержка автономного размещения не требуется, то HTTP-модуль является лучшим вариантом. 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:

  • Thread. CurrentPrincipal. Thread.CurrentPrincipal. Это свойство является стандартным способом установки участника потока в .NET. This property is the standard way to set the thread’s principal in .NET.
  • HttpContext. Current. пользователь. HttpContext.Current.User. Это свойство относится к ASP.NET. This property is specific to ASP.NET.

В следующем коде показано, как задать субъект: The following code shows how to set the principal:

Для веб-хостинга необходимо задать участника в обоих местах. в противном случае контекст безопасности может стать несогласованным. For web-hosting, you must set the principal in both places; otherwise the security context may become inconsistent. Однако для размещения в собственном размещении HttpContext. Current имеет значение null. For self-hosting, however, HttpContext.Current is null. Для обеспечения того, чтобы код не зависят от узла, необходимо проверить наличие значения null перед назначением HttpContext. Current, как показано ниже. 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.

  • Фильтры авторизации выполняются перед действием контроллера. Authorization filters run before the controller action. Если запрос не имеет полномочий, фильтр возвращает сообщение об ошибке и действие не вызывается. If the request is not authorized, the filter returns an error response, and the action is not invoked.
  • В рамках действия контроллера можно получить текущего участника из свойства ApiController. User . Within a controller action, you can get the current principal from the ApiController.User property. Например, можно отфильтровать список ресурсов на основе имени пользователя, возвращая только те ресурсы, которые принадлежат этому пользователю. For example, you might filter a list of resources based on the user name, returning only those resources that belong to that user.

Использование атрибута [авторизовать] Using the [Authorize] Attribute

Веб-API предоставляет встроенный фильтр авторизации, AuthorizeAttribute. Web API provides a built-in authorization filter, AuthorizeAttribute. Этот фильтр проверяет, прошел ли пользователь проверку подлинности. This filter checks whether the user is authenticated. В противном случае возвращается код состояния HTTP 401 (несанкционированный) без вызова действия. 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 individual actions.

Глобально. чтобы ограничить доступ для каждого контроллера веб-API, добавьте фильтр AuthorizeAttribute в глобальный список фильтров: Globally: To restrict access for every Web API controller, add the AuthorizeAttribute filter to the global filter list:

Читайте также:  Все версии linux по порядку

Контроллер. чтобы ограничить доступ к конкретному контроллеру, добавьте фильтр в качестве атрибута к контроллеру: Controller: To restrict access for a specific controller, add the filter as an attribute to the controller:

Действие: чтобы ограничить доступ для определенных действий, добавьте атрибут в метод действия: Action: To restrict access for specific actions, add the attribute to the action method:

Кроме того, можно ограничить контроллер, а затем разрешить анонимный доступ к определенным действиям с помощью [AllowAnonymous] атрибута. Alternatively, you can restrict the controller and then allow anonymous access to specific actions, by using the [AllowAnonymous] attribute. В следующем примере Post метод ограничен, но Get метод допускает анонимный доступ. In the following example, the Post method is restricted, but the Get method allows anonymous access.

В предыдущих примерах фильтр позволяет любому пользователю, прошедшему проверку подлинности, получить доступ к ограниченным методам. поддерживаются только анонимные пользователи. Вы также можете ограничить доступ для конкретных пользователей или пользователей в конкретных ролях: 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:

Фильтр AuthorizeAttribute для контроллеров веб-API находится в пространстве имен System. Web. http . The AuthorizeAttribute filter for Web API controllers is located in the System.Web.Http namespace. Существует аналогичный фильтр для контроллеров MVC в пространстве имен System. Web. MVC , который несовместим с контроллерами веб-API. 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:

  • AuthorizeAttribute. AuthorizeAttribute. Расширьте этот класс для выполнения логики авторизации на основе текущего пользователя и ролей пользователя. Extend this class to perform authorization logic based on the current user and the user’s roles.
  • Аусоризатионфилтераттрибуте. AuthorizationFilterAttribute. Расширьте этот класс для выполнения синхронной логики авторизации, которая не обязательно основана на текущем пользователе или роли. Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role.
  • Иаусоризатионфилтер. IAuthorizationFilter. Реализуйте этот интерфейс для выполнения логики асинхронной авторизации. Например, если логика авторизации выполняет асинхронный ввод-вывод или сетевые вызовы. Implement this interface to perform asynchronous authorization logic; for example, if your authorization logic makes asynchronous I/O or network calls. (Если логика авторизации привязана к ЦП, проще создать производную от аусоризатионфилтераттрибуте, так как вам не нужно писать асинхронный метод.) (If your authorization logic is CPU-bound, it is simpler to derive from AuthorizationFilterAttribute, because then you don’t need to write an asynchronous method.)

На следующей диаграмме показана иерархия классов для класса AuthorizeAttribute . The following diagram shows the class hierarchy for the AuthorizeAttribute class.

Authentication and Authorization in ASP.NET Web API

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.

  • Authentication is knowing the identity of the user. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice.
  • Authorization is deciding whether a user is allowed to perform an action. For example, Alice has permission to get a resource but not create a resource.

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.

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.

Читайте также:  Windows paint как рисовать

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:

  • An HTTP module sees all requests that go through the ASP.NET pipeline. A message handler only sees requests that are routed to Web API.
  • You can set per-route message handlers, which lets you apply an authentication scheme to a specific route.
  • HTTP modules are specific to IIS. Message handlers are host-agnostic, so they can be used with both web-hosting and self-hosting.
  • HTTP modules participate in IIS logging, auditing, and so on.
  • HTTP modules run earlier in the pipeline. If you handle authentication in a message handler, the principal does not get set until the handler runs. Moreover, the principal reverts back to the previous principal when the response leaves the message handler.

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:

  • Thread.CurrentPrincipal. This property is the standard way to set the thread’s principal in .NET.
  • HttpContext.Current.User. This property is specific to ASP.NET.

The following code shows how to set the principal:

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.

  • Authorization filters run before the controller action. If the request is not authorized, the filter returns an error response, and the action is not invoked.
  • Within a controller action, you can get the current principal from the ApiController.User property. For example, you might filter a list of resources based on the user name, returning only those resources that belong to that user.

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 individual actions.

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

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

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

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.

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:

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:

  • AuthorizeAttribute. Extend this class to perform authorization logic based on the current user and the user’s roles.
  • AuthorizationFilterAttribute. Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role.
  • IAuthorizationFilter. Implement this interface to perform asynchronous authorization logic; for example, if your authorization logic makes asynchronous I/O or network calls. (If your authorization logic is CPU-bound, it is simpler to derive from AuthorizationFilterAttribute, because then you don’t need to write an asynchronous method.)

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

Оцените статью