ClientRoleProvider.IsUserInRole(String, String) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Recebe um valor que indica se o utilizador especificado está no papel 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
O nome do usuário.
- roleName
- String
O nome da função.
Devoluções
true se o utilizador especificado estiver no papel especificado; false se o utilizador especificado não estiver autenticado ou não estiver na função especificada.
Exceções
username é Empty ou null.
-ou-
username não é o nome de utilizador do utilizador atual e autenticado.
Exemplos
O código de exemplo seguinte demonstra como aceder diretamente a este método para determinar se o utilizador está num determinado papel. Este código testa primeiro se o login do utilizador expirou. É necessária uma referência explícita ClientRoleProvider para chamar o GetRolesForUser método, pelo que a mesma referência é usada para chamar o IsUserInRole método. Se o utilizador estiver no papel de "gestor", este código chama um PerformManagerTask método, que não é fornecido.
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
Observações
Pode determinar se um utilizador autenticado está num determinado papel chamando o IsInRole método do IPrincipal devolvido pela staticThread.CurrentPrincipal propriedade. Para aplicações configuradas para usar serviços de aplicação cliente, esta propriedade devolve um ClientRolePrincipal. Como esta classe implementa a IPrincipal interface, não precisas de a referenciar explicitamente. O ClientRolePrincipal.IsInRole método chama internamente o IsUserInRole método. O IsUserInRole método utiliza o GetRolesForUser método para determinar se o utilizador indicado por username está no papel indicado por roleName.
O fornecedor de serviços armazena em cache a informação dos papéis sobre o sistema de ficheiros local para evitar chamadas de serviço desnecessárias. Para mais informações, consulte a ClientRoleProvider visão geral da turma.