Edit

Share via


ClientRolePrincipal.IsInRole(String) Method

Definition

Gets a value indicating whether the user represented by the ClientRolePrincipal is in the specified role.

public:
 virtual bool IsInRole(System::String ^ role);
public bool IsInRole (string role);
abstract member IsInRole : string -> bool
override this.IsInRole : string -> bool
Public Function IsInRole (role As String) As Boolean

Parameters

role
String

The role to check.

Returns

true if the user is in the specified role; false if the user is not in the specified role or is not authenticated.

Implements

Examples

The following example code demonstrates how to use this method to display a button only when the user is in the "manager" role. This example requires a Button named managerOnlyButton with an initial Visible property value of false.

private void DisplayButtonForManagerRole()
{
    try
    {
        ClientRolePrincipal rolePrincipal =
            System.Threading.Thread.CurrentPrincipal 
            as ClientRolePrincipal;

        if (rolePrincipal != null && rolePrincipal.IsInRole("manager"))
        {
            managerOnlyButton.Visible = true;
        }
    }
    catch (System.Net.WebException)
    {
        MessageBox.Show("Unable to access the roles service.",
            "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}
Private Sub DisplayButtonForManagerRole()

    Try

        Dim rolePrincipal As ClientRolePrincipal = TryCast( _
            System.Threading.Thread.CurrentPrincipal, ClientRolePrincipal)

        If rolePrincipal IsNot Nothing And _
            rolePrincipal.IsInRole("manager") Then

            managerOnlyButton.Visible = True

        End If

    Catch ex As System.Net.WebException

        MessageBox.Show("Unable to access the role service.", _
            "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)

    End Try

End Sub

Remarks

Normally, you will call the IsInRole method of the IPrincipal returned by the static Thread.CurrentPrincipal property. However, you can cast the CurrentPrincipal property value to a ClientRolePrincipal reference to call this method explicitly, as demonstrated in the Example section.

The IsInRole method will always return false if the user login has expired. This will not occur if your application calls the IsInRole method one time shortly after authentication. If your application must retrieve user roles at other times, you might want to add code to revalidate users whose login has expired. If all valid users are assigned to roles, you can determine whether the login has expired by calling the ClientRoleProvider.GetRolesForUser method. If no roles are returned, the login has expired. For an example of this functionality, see the GetRolesForUser method. This functionality is only necessary if you have selected Require users to log on again whenever the server cookie expires in your application configuration.

Applies to

See also