Compartir vía


ClientRoleProvider.IsUserInRole(String, String) Método

Definición

Obtiene un valor que indica si el usuario especificado está en el rol especificado.

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

Parámetros

username
String

Nombre del usuario.

roleName
String

Nombre del rol.

Devoluciones

true si el usuario especificado está en el rol especificado; false si el usuario especificado no está autenticado o no está en el rol especificado.

Excepciones

username es Empty o null.

-o-

username no es el nombre de usuario del usuario autenticado actual.

El usuario ya no está autenticado.

-o-

El servicio roles no está disponible.

Ejemplos

En el código de ejemplo siguiente se muestra cómo acceder directamente a este método para determinar si el usuario está en un rol determinado. Este código comprueba primero si el inicio de sesión del usuario ha expirado. Se requiere una referencia de ClientRoleProvider explícita para llamar al método GetRolesForUser, por lo que se usa la misma referencia para llamar al método IsUserInRole. Si el usuario está en el rol "administrador", este código llama a un método PerformManagerTask, que no se proporciona.

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

Comentarios

Puede determinar si un usuario autenticado está en un rol determinado llamando al método IsInRole del IPrincipal devuelto por la propiedad staticThread.CurrentPrincipal. Para que las aplicaciones configuradas usen servicios de aplicaciones cliente, esta propiedad devuelve un ClientRolePrincipal. Dado que esta clase implementa la interfaz IPrincipal, no es necesario hacer referencia a ella explícitamente. El método ClientRolePrincipal.IsInRole llama internamente al método IsUserInRole. El método IsUserInRole usa el método GetRolesForUser para determinar si el usuario indicado por username está en el rol indicado por roleName.

El proveedor de servicios almacena en caché la información del rol sobre el sistema de archivos local para evitar llamadas de servicio innecesarias. Para obtener más información, consulte la introducción a la clase ClientRoleProvider.

Se aplica a

Consulte también