SqlConnection.ChangePassword Método

Definição

Altera a senha do SQL Server.Changes the SQL Server password.

Sobrecargas

ChangePassword(String, String)

Altera a senha do SQL Server do usuário indicado na cadeia de conexão para a nova senha fornecida.Changes the SQL Server password for the user indicated in the connection string to the supplied new password.

ChangePassword(String, SqlCredential, SecureString)

Altera a senha do SQL Server para o usuário indicado no objeto SqlCredential.Changes the SQL Server password for the user indicated in the SqlCredential object.

ChangePassword(String, String)

Altera a senha do SQL Server do usuário indicado na cadeia de conexão para a nova senha fornecida.Changes the SQL Server password for the user indicated in the connection string to the supplied new password.

public:
 static void ChangePassword(System::String ^ connectionString, System::String ^ newPassword);
public static void ChangePassword (string connectionString, string newPassword);
static member ChangePassword : string * string -> unit
Public Shared Sub ChangePassword (connectionString As String, newPassword As String)

Parâmetros

connectionString
String

A cadeia de conexão que contém informações suficientes para conectar-se ao servidor que você deseja.The connection string that contains enough information to connect to the server that you want. A cadeia de conexão deve conter a ID de usuário e a senha atual.The connection string must contain the user ID and the current password.

newPassword
String

A nova senha a ser definida.The new password to set. Essa senha deve estar em conformidade com as políticas de segurança de senha definidas no servidor, incluindo o tamanho mínimo, os requisitos de caracteres específicos e assim por diante.This password must comply with any password security policy set on the server, including minimum length, requirements for specific characters, and so on.

Exceções

A cadeia de conexão inclui a opção de usar segurança integrada.The connection string includes the option to use integrated security.

OuOr

O newPassword ultrapassa 128 caracteres.The newPassword exceeds 128 characters.

O parâmetro connectionString ou newPassword é nulo.Either the connectionString or the newPassword parameter is null.

Exemplos

Veja a seguir um exemplo simples de alteração de senha:The following is a simple example of changing a password:

class Program {
   static void Main(string[] args) {
      System.Data.SqlClient.SqlConnection.ChangePassword(
        "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
       "new_password");
   }
}
Module Module1
    Sub Main()
System.Data.SqlClient.SqlConnection.ChangePassword(
        "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
       "new_password")
    End Sub
End Module

O aplicativo de console a seguir demonstra os problemas envolvidos na alteração da senha de um usuário, pois a senha atual expirou.The following console application demonstrates the issues involved in changing a user's password because the current password has expired.

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        try
        {
            DemonstrateChangePassword();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine();
    }

    private static void DemonstrateChangePassword()
    {
        // Retrieve the connection string. In a production application,
        // this string should not be contained within the source code.
        string connectionString = GetConnectionString();

        using (SqlConnection cnn = new SqlConnection())
        {
            for (int i = 0; i <= 1; i++)
            {
                // Run this loop at most two times. If the first attempt fails,
                // the code checks the Number property of the SqlException object.
                // If that contains the special values 18487 or 18488, the code
                // attempts to set the user's password to a new value.
                // Assuming this succeeds, the second pass through
                // successfully opens the connection.
                // If not, the exception handler catches the exception.
                try
                {
                    cnn.ConnectionString = connectionString;
                    cnn.Open();
                    // Once this succeeds, just get out of the loop.
                    // No need to try again if the connection is already open.
                    break;
                }
                catch (SqlException ex)
                {
                    if (i == 0 && ((ex.Number == 18487) || (ex.Number == 18488)))
                    {
                        // You must reset the password.
                        connectionString =
                            ModifyConnectionString(connectionString,
                            GetNewPassword());
                    }
                    else
                    {
                        // Bubble all other SqlException occurrences
                        // back up to the caller.
                        throw;
                    }
                }
            }
            SqlCommand cmd = new SqlCommand(
                "SELECT ProductID, Name FROM Product", cnn);
            // Use the connection and command here...
        }
    }

    private static string ModifyConnectionString(
        string connectionString, string NewPassword)
    {

        // Use the SqlConnectionStringBuilder class to modify the
        // password portion of the connection string.
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(connectionString);
        builder.Password = NewPassword;
        return builder.ConnectionString;
    }

    private static string GetNewPassword()
    {
        // In a real application, you might display a modal
        // dialog box to retrieve the new password. The concepts
        // are the same as for this simple console application, however.
        Console.Write("Your password must be reset. Enter a new password: ");
        return Console.ReadLine();
    }

    private static string GetConnectionString()
    {
        // For this demonstration, the connection string must
        // contain both user and password information. In your own
        // application, you might want to retrieve this setting
        // from a config file, or from some other source.

        // In a production application, you would want to
        // display a modal form that could gather user and password
        // information.
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(
            "Data Source=(local);Initial Catalog=AdventureWorks");

        Console.Write("Enter your user id: ");
        builder.UserID = Console.ReadLine();
        Console.Write("Enter your password: ");
        builder.Password = Console.ReadLine();

        return builder.ConnectionString;
    }
}
Option Explicit On
Option Strict On

Imports System.Data
Imports System.Data.SqlClient

Module Module1
    Sub Main()
        Try
            DemonstrateChangePassword()
        Catch ex As Exception
            Console.WriteLine("Error: " & ex.Message)
        End Try
        Console.WriteLine("Press ENTER to continue...")
        Console.ReadLine()
    End Sub

    Private Sub DemonstrateChangePassword()
        Dim connectionString As String = GetConnectionString()
        Using cnn As New SqlConnection()
            For i As Integer = 0 To 1
                ' Run this loop at most two times. If the first attempt fails, 
                ' the code checks the Number property of the SqlException object.
                ' If that contains the special values 18487 or 18488, the code 
                ' attempts to set the user's password to a new value. 
                ' Assuming this succeeds, the second pass through 
                ' successfully opens the connection.
                ' If not, the exception handler catches the exception.
                Try
                    cnn.ConnectionString = connectionString
                    cnn.Open()
                    ' Once this succeeds, just get out of the loop.
                    ' No need to try again if the connection is already open.
                    Exit For

                Catch ex As SqlException _
                 When (i = 0 And (ex.Number = 18487 Or ex.Number = 18488))
                    ' You must reset the password.
                    connectionString = ModifyConnectionString( _
                     connectionString, GetNewPassword())

                Catch ex As SqlException
                    ' Bubble all other SqlException occurrences
                    ' back up to the caller.
                    Throw
                End Try
            Next
            Dim cmd As New SqlCommand("SELECT ProductID, Name FROM Product", cnn)
            ' Use the connection and command here...
        End Using
    End Sub

    Private Function ModifyConnectionString( _
     ByVal connectionString As String, ByVal NewPassword As String) As String

        ' Use the SqlConnectionStringBuilder class to modify the
        ' password portion of the connection string. 
        Dim builder As New SqlConnectionStringBuilder(connectionString)
        builder.Password = NewPassword
        Return builder.ConnectionString
    End Function

    Private Function GetNewPassword() As String
        ' In a real application, you might display a modal
        ' dialog box to retrieve the new password. The concepts
        ' are the same as for this simple console application, however.
        Console.Write("Your password must be reset. Enter a new password: ")
        Return Console.ReadLine()
    End Function

    Private Function GetConnectionString() As String
        ' For this demonstration, the connection string must
        ' contain both user and password information. In your own
        ' application, you might want to retrieve this setting
        ' from a config file, or from some other source.

        ' In a production application, you would want to 
        ' display a modal form that could gather user and password
        ' information.
        Dim builder As New SqlConnectionStringBuilder( _
         "Data Source=(local);Initial Catalog=AdventureWorks")

        Console.Write("Enter your user id: ")
        builder.UserID = Console.ReadLine()
        Console.Write("Enter your password: ")
        builder.Password = Console.ReadLine()

        Return builder.ConnectionString
    End Function
End Module

Comentários

Quando você está usando SQL Server no Windows Server, os desenvolvedores podem aproveitar a funcionalidade que permite que o aplicativo cliente forneça a senha atual e uma nova para alterar a senha existente.When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Os aplicativos podem implementar funcionalidades como solicitar ao usuário uma nova senha durante o logon inicial, se a antiga tiver expirado, e essa operação puder ser concluída sem a intervenção do administrador.Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention.

O ChangePassword método altera a senha SQL Server para o usuário indicado no parâmetro fornecido connectionString para o valor fornecido no newPassword parâmetro.The ChangePassword method changes the SQL Server password for the user indicated in the supplied connectionString parameter to the value supplied in the newPassword parameter. Se a cadeia de conexão incluir a opção de segurança integrada (ou seja, "Integrated Security = true" ou equivalente), uma exceção será lançada.If the connection string includes the option for integrated security (that is, "Integrated Security=True" or the equivalent), an exception is thrown.

Para determinar que a senha expirou, chamar o Open método gera um SqlException .To determine that the password has expired, calling the Open method raises a SqlException. Para indicar que a senha contida na cadeia de conexão deve ser redefinida, a Number propriedade da exceção contém o valor de status 18487 ou 18488.In order to indicate that the password that is contained within the connection string must be reset, the Number property for the exception contains the status value 18487 or 18488. O primeiro valor (18487) indica que a senha expirou e o segundo (18488) indica que a senha deve ser redefinida antes de fazer logon.The first value (18487) indicates that the password has expired and the second (18488) indicates that the password must be reset before logging in.

Esse método abre sua própria conexão com o servidor, solicita a alteração de senha e fecha a conexão assim que ela é concluída.This method opens its own connection to the server, requests the password change, and closes the connection as soon as it has completed. Essa conexão não é recuperada de, nem retornada para o pool de conexões SQL Server.This connection is not retrieved from, nor returned to, the SQL Server connection pool.

Aplica-se a

ChangePassword(String, SqlCredential, SecureString)

Altera a senha do SQL Server para o usuário indicado no objeto SqlCredential.Changes the SQL Server password for the user indicated in the SqlCredential object.

public:
 static void ChangePassword(System::String ^ connectionString, System::Data::SqlClient::SqlCredential ^ credential, System::Security::SecureString ^ newPassword);
public:
 static void ChangePassword(System::String ^ connectionString, System::Data::SqlClient::SqlCredential ^ credential, System::Security::SecureString ^ newSecurePassword);
public static void ChangePassword (string connectionString, System.Data.SqlClient.SqlCredential credential, System.Security.SecureString newPassword);
public static void ChangePassword (string connectionString, System.Data.SqlClient.SqlCredential credential, System.Security.SecureString newSecurePassword);
static member ChangePassword : string * System.Data.SqlClient.SqlCredential * System.Security.SecureString -> unit
static member ChangePassword : string * System.Data.SqlClient.SqlCredential * System.Security.SecureString -> unit
Public Shared Sub ChangePassword (connectionString As String, credential As SqlCredential, newPassword As SecureString)
Public Shared Sub ChangePassword (connectionString As String, credential As SqlCredential, newSecurePassword As SecureString)

Parâmetros

connectionString
String

A cadeia de conexão que contém informações suficientes para se conectar a um servidor.The connection string that contains enough information to connect to a server. A cadeia de conexão não deve usar nenhuma das palavras-chave de cadeia de conexão a seguir: Integrated Security = true, UserId, Password ou ContextConnection = true.The connection string should not use any of the following connection string keywords: Integrated Security = true, UserId, or Password; or ContextConnection = true.

credential
SqlCredential

Um objeto SqlCredential.A SqlCredential object.

newPasswordnewSecurePassword
SecureString

A nova senha.newPasswordThe new password.newPassword precisa ser somente leitura.must be read only. A senha também deve estar em conformidade com a política de segurança de senha definida no servidor (por exemplo, requisitos e comprimento mínimos para caracteres específicos).The password must also comply with any password security policy set on the server (for example, minimum length and requirements for specific characters).

Exceções

A cadeia de conexão contém qualquer combinação de UserId, Password ou Integrated Security=true.The connection string contains any combination of UserId, Password, or Integrated Security=true.

- ou --or-

A cadeia de conexão contém Context Connection=true.The connection string contains Context Connection=true.

- ou --or-

newSecurePassword (ou newPassword) tem mais de 128 caracteres.newSecurePassword (or newPassword) is greater than 128 characters.

- ou --or-

newSecurePassword (ou newPassword) não é somente leitura.newSecurePassword (or newPassword) is not read only.

- ou --or-

newSecurePassword (ou newPassword) é uma cadeia de caracteres vazia.newSecurePassword (or newPassword) is an empty string.

Um dos parâmetros (connectionString, credential ou newSecurePassword) é nulo.One of the parameters (connectionString, credential, or newSecurePassword) is null.

Aplica-se a