ClientRoleProvider.IsUserInRole(String, String) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает значение, позволяющее определить, может ли заданный пользователь выполнять указанную роль.
public:
override bool IsUserInRole(System::String ^ username, System::String ^ roleName);
public override bool IsUserInRole (string username, string roleName);
override this.IsUserInRole : string * string -> bool
Public Overrides Function IsUserInRole (username As String, roleName As String) As Boolean
Параметры
- username
- String
Имя пользователя.
- roleName
- String
Имя роли.
Возвращаемое значение
Если заданный пользователь выполняет указанную роль, значение true
; если заданный пользователь не прошел проверку подлинности или не выполняет такую роль, значение false
.
Исключения
username
имеет значение Empty или null
.
-или-
Если параметр username
не является именем текущего пользователя, прошедшего проверку подлинности.
Пользователь больше не считается прошедшим проверку подлинности.
-или-
Служба ролей недоступна.
Примеры
В следующем примере кода показано, как напрямую получить доступ к этому методу, чтобы определить, находится ли пользователь в определенной роли. Этот код сначала проверяет, истек ли срок действия входа пользователя. Для вызова GetRolesForUser метода требуется явная ClientRoleProvider ссылка, поэтому для вызова IsUserInRole метода используется та же ссылка. Если пользователь находится в роли "менеджер", этот код вызывает PerformManagerTask
метод, который не предоставляется.
private void AttemptManagerTask()
{
System.Security.Principal.IIdentity identity =
System.Threading.Thread.CurrentPrincipal.Identity;
// Return if the authentication type is not "ClientForms".
// This indicates that the user is logged out.
if (!identity.AuthenticationType.Equals("ClientForms")) return;
try
{
ClientRoleProvider provider =
(ClientRoleProvider)System.Web.Security.Roles.Provider;
String userName = identity.Name;
// Determine whether the user login has expired by attempting
// to retrieve roles from the service. Call the ResetCache method
// to ensure that the roles are retrieved from the service. If no
// roles are returned, then the login has expired. This assumes
// that every valid user has been assigned to one or more roles.
provider.ResetCache();
String[] roles = provider.GetRolesForUser(userName);
if (roles.Length == 0)
{
MessageBox.Show(
"Your login has expired. Please log in again to access " +
"the roles service.", "Attempting to access user roles...");
// Call ValidateUser with empty strings in order to
// display the login dialog box configured as a
// credentials provider.
if (!System.Web.Security.Membership.ValidateUser(
String.Empty, String.Empty))
{
MessageBox.Show("Unable to authenticate. " +
"Cannot retrieve user roles.", "Not logged in",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
if (provider.IsUserInRole(userName, "manager"))
{
PerformManagerTask();
}
}
catch (System.Net.WebException)
{
MessageBox.Show(
"Unable to access the remote service. " +
"Cannot retrieve user roles.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Private Sub AttemptManagerTask()
Dim identity As System.Security.Principal.IIdentity = _
System.Threading.Thread.CurrentPrincipal.Identity
' Return if the authentication type is not "ClientForms".
' This indicates that the user is logged out.
If Not identity.AuthenticationType.Equals("ClientForms") Then Return
Try
Dim provider As ClientRoleProvider = _
CType(System.Web.Security.Roles.Provider, ClientRoleProvider)
Dim userName As String = identity.Name
' Determine whether the user login has expired by attempting
' to retrieve roles from the service. Call the ResetCache method
' to ensure that the roles are retrieved from the service. If no
' roles are returned, then the login has expired. This assumes
' that every valid user has been assigned to one or more roles.
provider.ResetCache()
Dim roles As String() = provider.GetRolesForUser(userName)
If roles.Length = 0 Then
MessageBox.Show( _
"Your login has expired. Please log in again to access " & _
"the roles service.", "Attempting to access user roles...")
' Call ValidateUser with empty strings in order to
' display the login dialog box configured as a
' credentials provider.
If Not System.Web.Security.Membership.ValidateUser( _
String.Empty, String.Empty) Then
MessageBox.Show("Unable to authenticate. " & _
"Cannot retrieve user roles.", "Not logged in", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
End If
If provider.IsUserInRole(userName, "manager") Then
PerformManagerTask()
End If
Catch ex As System.Net.WebException
MessageBox.Show( _
"Unable to access the remote service. " & _
"Cannot retrieve user roles.", "Warning", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Комментарии
Вы можете определить, находится ли пользователь, прошедший проверку подлинности, в определенной роли, вызвав IsInRole метод объекта , IPrincipal возвращаемого свойством static
Thread.CurrentPrincipal . Для приложений, настроенных на использование служб клиентских приложений, это свойство возвращает класс ClientRolePrincipal. Поскольку этот класс реализует интерфейс IPrincipal , необязательно явно ссылаться на него. Метод ClientRolePrincipal.IsInRole внутренне вызывает IsUserInRole метод . Метод IsUserInRole использует метод , GetRolesForUser чтобы определить, находится ли пользователь, указанный параметром username
roleName
.
Поставщик служб кэширует сведения о роли локальной файловой системы, чтобы избежать ненужных вызовов служб. Дополнительные сведения см. в обзоре ClientRoleProvider класса.
Применяется к
См. также раздел
Обратная связь
https://aka.ms/ContentUserFeedback.
Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделеОтправить и просмотреть отзыв по