Безопасность. Проверка подлинности и авторизация в ASP.NET Web Forms и Blazor Security: Authentication and Authorization in ASP.NET Web Forms and Blazor
Миграция из приложения веб-форм ASP.NET в Blazor почти наверняка требует обновления проверки подлинности и авторизации, предполагая, что для приложения настроена проверка подлинности.Migrating from an ASP.NET Web Forms application to Blazor will almost certainly require updating how authentication and authorization are performed, assuming the application had authentication configured. В этой главе рассматривается миграция из модели универсального поставщика веб-форм ASP.NET (для членства, ролей и профилей пользователей) и работа с удостоверениями ASP.NET Core из Blazor приложений.This chapter will cover how to migrate from the ASP.NET Web Forms universal provider model (for membership, roles, and user profiles) and how to work with ASP.NET Core Identity from Blazor apps. Хотя в этой главе рассматриваются общие шаги и рекомендации, подробные инструкции и сценарии можно найти в документации, на которую имеются ссылки.While this chapter will cover the high-level steps and considerations, the detailed steps and scripts may be found in the referenced documentation.
Универсальные поставщики ASP.NETASP.NET universal providers
Начиная с ASP.NET 2,0 платформа веб-форм ASP.NET поддерживала модель поставщика для различных функций, включая членство.Since ASP.NET 2.0, the ASP.NET Web Forms platform has supported a provider model for a variety of features, including membership. Поставщик универсального членства вместе с дополнительным поставщиком ролей обычно развертывается с помощью приложений ASP.NET Web Forms.The universal membership provider, along with the optional role provider, is commonly deployed with ASP.NET Web Forms applications. Он обеспечивает надежный и безопасный способ управления проверкой подлинности и авторизацией, которая будет работать уже сегодня.It offers a robust and secure way to manage authentication and authorization that continues to work well today. Последнее предложение этих универсальных поставщиков доступно в виде пакета NuGet, Microsoft. AspNet. Providers.The most recent offering of these universal providers is available as a NuGet package, Microsoft.AspNet.Providers.
Универсальные поставщики работать с схемой базы данных SQL, которая включает такие таблицы aspnet_Applications
, как,, aspnet_Membership
aspnet_Roles
и aspnet_Users
.The Universal Providers work with a SQL database schema that includes tables like aspnet_Applications
, aspnet_Membership
, aspnet_Roles
, and aspnet_Users
. При настройке с помощью командыaspnet_regsql.exeпоставщики устанавливают таблицы и хранимые процедуры, которые предоставляют все необходимые запросы и команды для работы с базовыми данными.When configured by running the aspnet_regsql.exe command, the providers install tables and stored procedures that provide all of the necessary queries and commands to work with the underlying data. Схема базы данных и эти хранимые процедуры несовместимы с более новыми ASP.NET Identity и ASP.NET Core системами удостоверений, поэтому существующие данные должны быть перенесены в новую систему.The database schema and these stored procedures are not compatible with newer ASP.NET Identity and ASP.NET Core Identity systems, so existing data must be migrated into the new system. На рис. 1 показан пример схемы таблицы, настроенной для универсальных поставщиков.Figure 1 shows an example table schema configured for universal providers.
Универсальный поставщик обрабатывает пользователей, членство, роли и профили.The universal provider handles users, membership, roles, and profiles. Пользователям назначаются глобальные уникальные идентификаторы и основные сведения, такие как userId, userName и т. д., хранятся в aspnet_Users
таблице.Users are assigned globally unique identifiers and basic information like userId, userName etc. are stored in the aspnet_Users
table. Сведения о проверке подлинности, такие как пароль, формат пароля, Salt пароля, счетчики блокировки и сведения и т. д., хранятся в aspnet_Membership
таблице.Authentication information, such as password, password format, password salt, lockout counters and details, etc. are stored in the aspnet_Membership
table. Роли состоят только из имен и уникальных идентификаторов, которые назначаются пользователям через aspnet_UsersInRoles
таблицу взаимосвязей, предоставляя связь «многие ко многим».Roles consist simply of names and unique identifiers, which are assigned to users via the aspnet_UsersInRoles
association table, providing a many-to-many relationship.
Если существующая система использует роли в дополнение к членству, необходимо перенести учетные записи пользователей, связанные пароли, роли и членство в роли в ASP.NET Core удостоверение.If your existing system is using roles in addition to membership, you will need to migrate the user accounts, the associated passwords, the roles, and the role membership into ASP.NET Core Identity. Вам также, скорее всего, потребуется обновить код, в котором выполняется проверка ролей с помощью инструкций If, вместо этого использовать декларативные фильтры, атрибуты и (или) вспомогательные функции тегов.You will also most likely need to update your code where you're currently performing role checks using if statements to instead leverage declarative filters, attributes, and/or tag helpers. В конце этой главы мы рассмотрим рекомендации по миграции более подробно.We will review migration considerations in greater detail at the end of this chapter.
Настройка авторизации в веб-формахAuthorization configuration in Web Forms
Чтобы настроить Полномочный доступ к определенным страницам в приложении веб-форм ASP.NET, обычно вы указываете, что определенные страницы или папки недоступны для анонимных пользователей.To configure authorized access to certain pages in an ASP.NET Web Forms application, typically you specify that certain pages or folders are inaccessible to anonymous users. Эта конфигурация выполняется в файле web.config:This configuration is done in the web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms defaultUrl="~/home.aspx" loginUrl="~/login.aspx"
slidingExpiration="true" timeout="2880"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
В authentication
разделе конфигурации настраивается проверка подлинности с помощью форм для приложения.The authentication
configuration section sets up the forms authentication for the application. authorization
Раздел используется для запрета анонимных пользователей для всего приложения.The authorization
section is used to disallow anonymous users for the entire application. Однако можно предоставить более детализированные правила авторизации для каждого расположения, а также применить проверки авторизации на основе ролей.However, you can provide more granular authorization rules on a per-location basis as well as apply role-based authorization checks.
<location path="login.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Приведенная выше конфигурация при объединении с первой позволяет анонимным пользователям получать доступ к странице входа, переопределяя ограничение на уровне сайта для пользователей, не прошедших проверку подлинности.The above configuration, when combined with the first one, would allow anonymous users to access the login page, overriding the site-wide restriction on non-authenticated users.
<location path="/admin">
<system.web>
<authorization>
<allow roles="Administrators" />
<deny users="*" />
</authorization>
</system.web>
</location>
Приведенная выше конфигурация, в сочетании с другими, позволяет ограничивать доступ к /admin
папке и всем ее ресурсам членам роли "Администраторы".The above configuration, when combined with the others, restricts access to the /admin
folder and all resources within it to members of the "Administrators" role. Это ограничение можно также применить, поместив отдельный web.config
файл в /admin
корневую папку.This restriction could also be applied by placing a separate web.config
file within the /admin
folder root.
Код авторизации в веб-формахAuthorization code in Web Forms
Помимо настройки доступа с помощью web.config
, можно также программно настроить доступ и поведение в приложении веб-форм.In addition to configuring access using web.config
, you can also programmatically configure access and behavior in your Web Forms application. Например, можно ограничить возможность выполнения определенных операций или просмотра определенных данных в зависимости от роли пользователя.For instance, you can restrict the ability to perform certain operations or view certain data based on the user's role.
Этот код можно использовать как в логике кода программной части, так и на самой странице:This code can be used both in code-behind logic as well as in the page itself:
<% if (HttpContext.Current.User.IsInRole("Administrators")) { %>
<a href="/admin">Go To Admin</a>
<% } %>
Помимо проверки членства в роли пользователя, можно также определить, прошли ли они проверку подлинности (хотя часто это лучше выполнить с использованием конфигурации на основе расположения, описанной выше).In addition to checking user role membership, you can also determine if they are authenticated (though often this is better done using the location-based configuration covered above). Ниже приведен пример такого подхода.Below is an example of this approach.
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
{
MessageLabel.Text = "Only administrators can view this.";
SecretPanel.Visible = false;
}
}
В приведенном выше коде управление доступом на основе ролей (RBAC) используется для определения того, видимы ли определенные элементы страницы, например, в SecretPanel
зависимости от роли текущего пользователя.In the code above, role-based access control (RBAC) is used to determine whether certain elements of the page, such as a SecretPanel
, are visible based on the current user's role.
Как правило, приложения ASP.NET Web Forms настраивают безопасность в web.config
файле, а затем добавляют дополнительные проверки, если это необходимо на .aspx
страницах и связанных с ними .aspx.cs
файлах кода программной части.Typically, ASP.NET Web Forms applications configure security within the web.config
file and then add additional checks where needed in .aspx
pages and their related .aspx.cs
code-behind files. Большинство приложений используют универсального поставщика членства, часто с дополнительным поставщиком ролей.Most applications leverage the universal membership provider, frequently with the additional role provider.
Идентификация ASP.NET CoreASP.NET Core Identity
Несмотря на то, что по-прежнему выполняется проверка подлинности и авторизация, ASP.NET Core удостоверение использует другой набор абстракций и допущений по сравнению с универсальными поставщиками.Although still tasked with authentication and authorization, ASP.NET Core Identity uses a different set of abstractions and assumptions when compared to the universal providers. Например, Новая модель удостоверений поддерживает проверку подлинности третьих сторон, позволяя пользователям проходить проверку подлинности с помощью учетной записи социальных сетей или другого доверенного поставщика проверки подлинности.For example, the new Identity model supports third party authentication, allowing users to authenticate using a social media account or other trusted authentication provider. ASP.NET Core Identity поддерживает пользовательский интерфейс для часто необходимых страниц, таких как вход, выход и регистрация.ASP.NET Core Identity supports UI for commonly needed pages like login, logout, and register. Он использует EF Core для доступа к данным, а EF Core миграции для создания необходимой схемы, необходимой для поддержки ее модели данных.It leverages EF Core for its data access, and uses EF Core migrations to generate the necessary schema required to support its data model. Это Введение в идентификацию на ASP.NET Core предоставляет хороший обзор того, что входит в состав ASP.NET Core удостоверений и как приступить к работе с ним.This introduction to Identity on ASP.NET Core provides a good overview of what is included with ASP.NET Core Identity and how to get started working with it. Если вы еще не настроили удостоверение ASP.NET Core в приложении и его базе данных, оно поможет приступить к работе.If you haven't already set up ASP.NET Core Identity in your application and its database, it will help you get started.
Роли, утверждения и политикиRoles, claims, and policies
Универсальные поставщики и удостоверение ASP.NET Core поддерживают концепцию ролей.Both the universal providers and ASP.NET Core Identity support the concept of roles. Вы можете создавать роли для пользователей и назначать им роли.You can create roles for users and assign users to roles. Пользователи могут принадлежать любому количеству ролей, и вы можете проверить членство в роли в рамках реализации авторизации.Users can belong to any number of roles, and you can verify role membership as part of your authorization implementation.
Помимо ролей, ASP.NET Core Identity поддерживает концепции заявок и политик.In addition to roles, ASP.NET Core identity supports the concepts of claims and policies. Хотя роль должна соответствовать набору ресурсов, доступ к которым должен иметь пользователь этой роли, утверждение — это просто часть удостоверения пользователя.While a role should specifically correspond to a set of resources a user in that role should be able to access, a claim is simply part of a user's identity. Утверждение — это пара "имя-значение", которая представляет предметную тему, а не то, что может делать субъект.A claim is a name value pair that represents what the subject is, not what the subject can do.
Можно напрямую проверить утверждения пользователя и определить их на основе этих значений, будет ли пользователь предоставлять доступ к ресурсу.It is possible to directly inspect a user's claims and determine based on these values whether a user should be given access to a resource. Однако такие проверки часто повторяются и разбросаны по всей системе.However, such checks are often repetitive and scattered throughout the system. Лучшим подходом является определение политики.A better approach is to define a policy.
Политика авторизации состоит из одного или нескольких требований.An authorization policy consists of one or more requirements. Политики регистрируются как часть конфигурации службы авторизации в ConfigureServices
методе Startup.cs
.Policies are registered as part of the authorization service configuration in the ConfigureServices
method of Startup.cs
. Например, следующий фрагмент кода настраивает политику с именем "Канадиансонли", которая требует, чтобы пользователь получил утверждение страны со значением "Канада".For example, the following code snippet configures a policy called "CanadiansOnly", which has the requirement that the user has the Country claim with the value of "Canada".
services.AddAuthorization(options =>
{
options.AddPolicy("CanadiansOnly", policy => policy.RequireClaim(ClaimTypes.Country, "Canada"));
});
Дополнительные сведения о создании пользовательских политик см. в документации.You can learn more about how to create custom policies in the documentation.
Независимо от того, используете ли вы политики или роли, вы можете указать, что определенная страница в Blazor приложении требует, чтобы роль или политика с [Authorize]
атрибутом применялась с @attribute
директивой.Whether you're using policies or roles, you can specify that a particular page in your Blazor application requires that role or policy with the [Authorize]
attribute, applied with the @attribute
directive.
Требования к роли:Requiring a role:
@attribute [Authorize(Roles ="administrators")]
Требовать соблюдение политики:Requiring a policy be satisfied:
@attribute [Authorize(Policy ="CanadiansOnly")]
Если вам требуется доступ к состоянию проверки подлинности, ролям или утверждениям пользователя в коде, существует два основных способа реализации этой функции.If you need access to a user's authentication state, roles, or claims in your code, there are two primary ways to achieve this functionality. Первый — получение состояния проверки подлинности в виде каскадного параметра.The first is to receive the authentication state as a cascading parameter. Второй — доступ к состоянию с помощью внедренного AuthenticationStateProvider
.The second is to access the state using an injected AuthenticationStateProvider
. Сведения о каждом из этих подходов описаны в Blazor документации по безопасности.The details of each of these approaches are described in the Blazor Security documentation.
В следующем коде показано, как получить в AuthenticationState
качестве каскадного параметра:The following code shows how to receive the AuthenticationState
as a cascading parameter:
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
С помощью этого параметра можно получить пользователя, используя следующий код:With this parameter in place, you can get the user using this code:
var authState = await authenticationStateTask;
var user = authState.User;
В следующем коде показано, как внедрить AuthenticationStateProvider
:The following code shows how to inject the AuthenticationStateProvider
:
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider
Используя поставщик, вы можете получить доступ к пользователю с помощью следующего кода:With the provider in place, you can gain access to the user with the following code:
AuthenticationState authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
ClaimsPrincipal user = authState.User;
if (user.Identity.IsAuthenticated)
{
// work with user.Claims and/or user.Roles
}
Примечание. AuthorizeView
Компонент, рассмотренный далее в этой главе, предоставляет декларативный способ управления тем, что видит пользователь на странице или в компоненте.Note: The AuthorizeView
component, covered later in this chapter, provides a declarative way to control what a user sees on a page or component.
Для работы с пользователями и утверждениями (в Blazor серверных приложениях) также может потребоваться внедрить UserManager<T>
(использовать IdentityUser
для использования по умолчанию), который можно использовать для перечисления и изменения утверждений для пользователя.To work with users and claims (in Blazor Server applications) you may also need to inject a UserManager<T>
(use IdentityUser
for default) which you can use to enumerate and modify claims for a user. Сначала вставьте тип и присвойте его свойству:First inject the type and assign it to a property:
@inject UserManager<IdentityUser> MyUserManager
Затем используйте его для работы с утверждениями пользователя.Then use it to work with the user's claims. В следующем примере показано, как добавить и сохранить утверждение для пользователя.The following sample shows how to add and persist a claim on a user:
private async Task AddCountryClaim()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
var identityUser = await MyUserManager.FindByNameAsync(user.Identity.Name);
if (!user.HasClaim(c => c.Type == ClaimTypes.Country))
{
// stores the claim in the cookie
ClaimsIdentity id = new ClaimsIdentity();
id.AddClaim(new Claim(ClaimTypes.Country, "Canada"));
user.AddIdentity(id);
// save the claim in the database
await MyUserManager.AddClaimAsync(identityUser, new Claim(ClaimTypes.Country, "Canada"));
}
}
Если необходимо работать с ролями, используйте тот же подход.If you need to work with roles, follow the same approach. Может потребоваться внедрить RoleManager<T>
(использовать IdentityRole
для типа по умолчанию), чтобы перечислить сами роли и управлять ими.You may need to inject a RoleManager<T>
(use IdentityRole
for default type) to list and manage the roles themselves.
Примечание. В Blazor проектах сборки для выполнения этих операций необходимо предоставить API-интерфейсы сервера (вместо использования UserManager<T>
или RoleManager<T>
непосредственно).Note: In Blazor WebAssembly projects, you will need to provide server APIs to perform these operations (instead of using UserManager<T>
or RoleManager<T>
directly). BlazorКлиентское приложение сборки может управлять утверждениями и (или) ролями путем безопасного вызова конечных точек API, предоставляемых для этой цели.A Blazor WebAssembly client application would manage claims and/or roles by securely calling API endpoints exposed for this purpose.
Руководство по миграцииMigration guide
Переход с веб-форм ASP.NET и универсальных поставщиков на ASP.NET Core удостоверение требует выполнения нескольких действий:Migrating from ASP.NET Web Forms and universal providers to ASP.NET Core Identity requires several steps:
- Создание схемы базы данных удостоверений ASP.NET Core в целевой базе данныхCreate ASP.NET Core Identity database schema in the destination database
- Перенос данных из схемы универсального поставщика в ASP.NET Core схему удостоверенийMigrate data from universal provider schema to ASP.NET Core Identity schema
- Перенос конфигурации из в
web.config
по промежуточного слоя и службы, обычно вStartup.cs
Migrate configuration from theweb.config
to middleware and services, typically inStartup.cs
- Обновление отдельных страниц с помощью элементов управления и условных обозначений для использования вспомогательных функций тегов и новых интерфейсов API идентификации.Update individual pages using controls and conditionals to use tag helpers and new identity APIs.
В следующих разделах каждый этап рассматривается более подробно.Each of these steps is described in detail in the following sections.
Создание схемы удостоверений ASP.NET CoreCreating the ASP.NET Core Identity schema
Существует несколько способов создания необходимой табличной структуры, используемой для ASP.NET Core удостоверения.There are several ways to create the necessary table structure used for ASP.NET Core Identity. Проще всего создать новое веб-приложение ASP.NET Core.The simplest is to create a new ASP.NET Core Web application. Выберите веб-приложение, а затем измените проверку подлинности, чтобы использовать учетные записи отдельных пользователей.Choose Web Application and then change Authentication to use Individual User Accounts.
В командной строке можно сделать то же самое, выполнив команду dotnet new webapp -au Individual
.From the command line, you can do the same thing by running dotnet new webapp -au Individual
. После создания приложения запустите его и зарегистрируйтесь на сайте.Once the app has been created, run it and register on the site. Следует активировать страницу, подобную показанной ниже:You should trigger a page like the one shown below:
Нажмите кнопку "применить миграции" и необходимо создать необходимые таблицы базы данных.Click on the "Apply Migrations" button and the necessary database tables should be created for you. Кроме того, файлы миграции должны отображаться в проекте, как показано ниже.In addition, the migration files should appear in your project, as shown:
Вы можете выполнить миграцию самостоятельно, не запуская веб-приложение с помощью этого средства командной строки:You can run the migration yourself, without running the web application, using this command-line tool:
dotnet ef database update
Если вы предпочитаете использовать сценарий для применения новой схемы к существующей базе данных, можно создать скрипты для этих миграций из командной строки.If you would rather run a script to apply the new schema to an existing database, you can script these migrations from the command-line. Выполните следующую команду, чтобы создать скрипт:Run this command to generate the script:
dotnet ef migrations script -o auth.sql
Приведенная выше команда создает скрипт SQL в выходном файле auth.sql
, который затем может выполняться в любой базе данных.The above command will produce a SQL script in the output file auth.sql
, which can then be run against whatever database you like. При возникновении проблем с выполнением dotnet ef
команд Убедитесь, что на компьютере установлены средства EF Core.If you have any trouble running dotnet ef
commands, make sure you have the EF Core tools installed on your system.
В случае, если у вас есть дополнительные столбцы в исходных таблицах, необходимо будет найти оптимальное расположение для этих столбцов в новой схеме.In the event you have additional columns on your source tables, you will need to identify the best location for these columns in the new schema. Как правило, столбцы, найденные в aspnet_Membership
таблице, должны быть сопоставлены с AspNetUsers
таблицей.Generally, columns found on the aspnet_Membership
table should be mapped to the AspNetUsers
table. Столбцы в aspnet_Roles
должны быть сопоставлены с AspNetRoles
.Columns on aspnet_Roles
should be mapped to AspNetRoles
. Все дополнительные столбцы таблицы будут aspnet_UsersInRoles
добавлены в AspNetUserRoles
таблицу.Any additional columns on the aspnet_UsersInRoles
table would be added to the AspNetUserRoles
table.
Также стоит рассмотреть возможность размещения дополнительных столбцов в отдельных таблицах.It's also worth considering putting any additional columns on separate tables. Так что в будущем миграция не потребуется учитывать такие настройки схемы удостоверений по умолчанию.So that future migrations won't need to take into account such customizations of the default identity schema.
Перенос данных от универсальных поставщиков в ASP.NET Core удостоверениеMigrating data from universal providers to ASP.NET Core Identity
После создания схемы целевой таблицы необходимо перенести записи пользователя и роли в новую схему.Once you have the destination table schema in place, the next step is to migrate your user and role records to the new schema. Полный список различий схем, включая столбцы, сопоставленные с новыми столбцами, можно найти здесь.A complete list of the schema differences, including which columns map to which new columns, can be found here.
Чтобы перенести пользователей из группы в новые таблицы удостоверений, выполните действия, описанные в документации.To migrate your users from membership to the new identity tables, you should follow the steps described in the documentation. После выполнения этих действий и предоставленного скрипта пользователям потребуется изменить пароль при следующем входе в систему.After following these steps and the script provided, your users will need to change their password the next time they log in.
Можно выполнить миграцию паролей пользователей, но процесс является гораздо более сложным.It is possible to migrate user passwords but the process is much more involved. Требовать от пользователей обновления паролей в рамках процесса миграции и поощрение их использования новых, уникальных паролей, скорее всего, приведет к повышению общей безопасности приложения.Requiring users to update their passwords as part of the migration process, and encouraging them to use new, unique passwords, is likely to enhance the overall security of the application.
Перенос параметров безопасности из web.config в Startup.csMigrating security settings from web.config to Startup.cs
Как отмечалось выше, поставщики членства и ролей ASP.NET настраиваются в файле приложения web.config
.As noted above, ASP.NET membership and role providers are configured in the application's web.config
file. Поскольку ASP.NET Core приложения не привязаны к службам IIS и используют отдельную систему для настройки, эти параметры должны быть настроены в другом расположении.Since ASP.NET Core apps are not tied to IIS and use a separate system for configuration, these settings must be configured elsewhere. В большинстве случаев ASP.NET Core удостоверение настраивается в Startup.cs
файле.For the most part, ASP.NET Core Identity is configured in the Startup.cs
file. Откройте созданный ранее веб-проект (чтобы создать схему таблицы удостоверений) и проверьте его Startup.cs
файл.Open the web project that was created earlier (to generate the identity table schema) and review its Startup.cs
file.
Метод ConfigureServices по умолчанию добавляет поддержку для EF Core и удостоверения.The default ConfigureServices method adds support for EF Core and Identity:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
}
AddDefaultIdentity
Метод расширения используется для настройки удостоверения для использования значения по умолчанию ApplicationDbContext
и IdentityUser
типа платформы.The AddDefaultIdentity
extension method is used to configure Identity to use the default ApplicationDbContext
and the framework's IdentityUser
type. Если вы используете настраиваемый объект IdentityUser
, обязательно укажите его тип.If you're using a custom IdentityUser
, be sure to specify its type here. Если эти методы расширения не работают в приложении, проверьте наличие соответствующих инструкций using и убедитесь, что у вас есть необходимые ссылки на пакет NuGet.If these extension methods aren't working in your application, check that you have the appropriate using statements and that you have the necessary NuGet package references. Например, в проекте должна быть установлена ссылка на несколько версий Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.AspNetCore.Identity.UI
пакетов и.For example, your project should have some version of the Microsoft.AspNetCore.Identity.EntityFrameworkCore
and Microsoft.AspNetCore.Identity.UI
packages referenced.
Кроме того, в Startup.cs
вы должны увидеть необходимое по промежуточного слоя, настроенное для сайта.Also in Startup.cs
you should see the necessary middleware configured for the site. В частности, UseAuthentication
и UseAuthorization
должны быть настроены и в нужном месте.Specifically, UseAuthentication
and UseAuthorization
should be set up, and in the proper location.
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
ASP.NET Identity не настраивает анонимный или ролевой доступ к расположениям из Startup.cs
.ASP.NET Identity does not configure anonymous or role-based access to locations from Startup.cs
. Необходимо перенести данные конфигурации авторизации, зависящие от местоположения, в фильтры в ASP.NET Core.You will need to migrate any location-specific authorization configuration data to filters in ASP.NET Core. Запишите, какие папки и страницы потребует таких обновлений.Make note of which folders and pages will require such updates. Эти изменения будут внесены в следующий раздел.You will make these changes in the next section.
Обновление отдельных страниц для использования абстракций ASP.NET Core удостоверенийUpdating individual pages to use ASP.NET Core Identity abstractions
В приложении веб-форм ASP.NET, если у вас есть web.config
Параметры, запрещающие доступ к определенным страницам или папкам анонимным пользователям, эти изменения необходимо перенести, добавив [Authorize]
атрибут на такие страницы:In your ASP.NET Web Forms application, if you had web.config
settings to deny access to certain pages or folders to anonymous users, you would migrate these changes by adding the [Authorize]
attribute to such pages:
@attribute [Authorize]
Если у вас еще есть отказ в доступе, за исключением пользователей, принадлежащих определенной роли, это поведение можно перенести, добавив атрибут, указывающий роль:If you further had denied access except to those users belonging to a certain role, you would likewise migrate this behavior by adding an attribute specifying a role:
@attribute [Authorize(Roles ="administrators")]
[Authorize]
Атрибут работает только для @page
компонентов, достигнутых через Blazor маршрутизатор.The [Authorize]
attribute only works on @page
components that are reached via the Blazor Router. Атрибут не работает с дочерними компонентами, которые вместо этого следует использовать AuthorizeView
.The attribute does not work with child components, which should instead use AuthorizeView
.
При наличии логики в разметке страницы для определения, следует ли отображать некоторый код для определенного пользователя, его можно заменить на AuthorizeView
компонент.If you have logic within page markup for determining whether to display some code to a certain user, you can replace this with the AuthorizeView
component. Компонент аусоризевиев выборочно ОТОБРАЖАЕТ пользовательский интерфейс в зависимости от того, имеет ли пользователь разрешение на его просмотр.The AuthorizeView component selectively displays UI depending on whether the user is authorized to see it. Он также предоставляет context
переменную, которая может использоваться для доступа к сведениям о пользователе.It also exposes a context
variable that can be used to access user information.
<AuthorizeView>
<Authorized>
<h1>Hello, @context.User.Identity.Name!</h1>
<p>You can only see this content if you are authenticated.</p>
</Authorized>
<NotAuthorized>
<h1>Authentication Failure!</h1>
<p>You are not signed in.</p>
</NotAuthorized>
</AuthorizeView>
Вы можете получить доступ к состоянию проверки подлинности в рамках процедурной логики, обратившись к пользователю из Task<AuthenticationState
настроенного с помощью [CascadingParameter]
атрибута.You can access the authentication state within procedural logic by accessing the user from a Task<AuthenticationState
configured with the [CascadingParameter]
attribute. Эта конфигурация позволит получить доступ к пользователю, который позволит определить, прошли ли они проверку подлинности, и принадлежат ли они к определенной роли.This configuration will get you access to the user, which can let you determine if they are authenticated and if they belong to a particular role. Если необходимо выполнить процедуру вычисления политики, можно внедрить экземпляр класса IAuthorizationService
и вызвать AuthorizeAsync
для него метод.If you need to evaluate a policy procedurally, you can inject an instance of the IAuthorizationService
and calls the AuthorizeAsync
method on it. В следующем примере кода показано, как получить сведения о пользователе и разрешить ему выполнять задачу, ограниченную content-editor
политикой.The following sample code demonstrates how to get user information and allow an authorized user to perform a task restricted by the content-editor
policy.
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService
<button @onclick="@DoSomething">Do something important</button>
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private async Task DoSomething()
{
var user = (await authenticationStateTask).User;
if (user.Identity.IsAuthenticated)
{
// Perform an action only available to authenticated (signed-in) users.
}
if (user.IsInRole("admin"))
{
// Perform an action only available to users in the 'admin' role.
}
if ((await AuthorizationService.AuthorizeAsync(user, "content-editor"))
.Succeeded)
{
// Perform an action only available to users satisfying the
// 'content-editor' policy.
}
}
}
AuthenticationState
Прежде чем можно будет привязать к каскадному параметру, необходимо настроить в качестве каскадного значения.The AuthenticationState
first need to be set up as a cascading value before it can be bound to a cascading parameter like this. Обычно это делается с помощью CascadingAuthenticationState
компонента.That's typically done using the CascadingAuthenticationState
component. Эта конфигурация обычно выполняется в App.razor
:This configuration is typically done in App.razor
:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData"
DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
ИтогиSummary
Blazor использует ту же модель безопасности, что и ASP.NET Core, которая является ASP.NET Core удостоверением.Blazor uses the same security model as ASP.NET Core, which is ASP.NET Core Identity. Миграция с универсальных поставщиков на ASP.NET Core удостоверения относительно проста, предполагая, что к исходной схеме данных не применено слишком много настроек.Migrating from universal providers to ASP.NET Core Identity is relatively straightforward, assuming not too much customization was applied to the original data schema. После переноса данных работа с проверкой подлинности и авторизацией в Blazor приложениях хорошо документирована, с возможностью настройки и программной поддержки для большинства требований безопасности.Once the data has been migrated, working with authentication and authorization in Blazor apps is well documented, with configurable as well as programmatic support for most security requirements.
СсылкиReferences
- Введение в удостоверение на ASP.NET CoreIntroduction to Identity on ASP.NET Core
- Миграция с аутентификации членства ASP.NET на ASP.NET Core 2,0 удостоверениеMigrate from ASP.NET Membership authentication to ASP.NET Core 2.0 Identity
- Перенесите проверку подлинности и удостоверение в ASP.NET CoreMigrate Authentication and Identity to ASP.NET Core
- BlazorПроверка подлинности ASP.NET Core и авторизацияASP.NET Core Blazor authentication and authorization