SqlConnection.ChangePassword Méthode

Définition

Change le mot de passe SQL Server.

Surcharges

ChangePassword(String, String)

Remplace le mot de passe SQL Server de l’utilisateur indiqué dans la chaîne de connexion par le nouveau mot de passe fourni.

ChangePassword(String, SqlCredential, SecureString)

Change le mot de passe SQL Server pour l’utilisateur indiqué dans l’objet SqlCredential.

ChangePassword(String, String)

Remplace le mot de passe SQL Server de l’utilisateur indiqué dans la chaîne de connexion par le nouveau mot de passe fourni.

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)

Paramètres

connectionString
String

Chaîne de connexion qui contient assez d'informations pour se connecter au serveur à utiliser. La chaîne de connexion doit contenir l'ID d'utilisateur et le mot de passe actuel.

newPassword
String

Le nouveau mot de passe à définir. Ce mot de passe doit se conformer à la stratégie de sécurité par mot de passe éventuellement définie sur le serveur, notamment la longueur minimale, les exigences en termes de caractères spécifiques, etc.

Exceptions

La chaîne de connexion inclut l’option pour utiliser la sécurité intégrée.

Ou

Le newPassword dépasse 128 caractères.

Le paramètre connectionString ou newPassword paramètre est null.

Exemples

Voici un exemple simple de modification d’un mot de passe :

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

L’application console suivante illustre les problèmes liés à la modification du mot de passe d’un utilisateur, car le mot de passe actuel a expiré.

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

Remarques

Lorsque vous utilisez SQL Server sur Windows Server, les développeurs peuvent tirer parti des fonctionnalités qui permettent à l’application cliente de fournir à la fois le mot de passe actuel et un nouveau mot de passe afin de modifier le mot de passe existant. Les applications peuvent implémenter des fonctionnalités telles que demander à l’utilisateur un nouveau mot de passe lors de la connexion initiale si l’ancien a expiré, et cette opération peut être effectuée sans intervention de l’administrateur.

La ChangePassword méthode modifie le mot de passe SQL Server pour l’utilisateur indiqué dans le paramètre fourni connectionString en valeur fournie dans le newPassword paramètre. Si le chaîne de connexion inclut l’option de sécurité intégrée (c’est-à-dire, « Integrated Security=True » ou l’équivalent), une exception est levée.

Pour déterminer que le mot de passe a expiré, l’appel de la Open méthode déclenche un SqlException. Pour indiquer que le mot de passe contenu dans le chaîne de connexion doit être réinitialisé, la Number propriété de l’exception contient la valeur status 18487 ou 18488. La première valeur (18487) indique que le mot de passe a expiré et la deuxième (18488) indique que le mot de passe doit être réinitialisé avant la connexion.

Cette méthode ouvre sa propre connexion au serveur, demande la modification du mot de passe et ferme la connexion dès qu’elle est terminée. Cette connexion n’est pas récupérée à partir du pool de connexions SQL Server et n’est pas retournée vers.

Voir aussi

S’applique à

ChangePassword(String, SqlCredential, SecureString)

Change le mot de passe SQL Server pour l’utilisateur indiqué dans l’objet SqlCredential.

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)

Paramètres

connectionString
String

Chaîne de connexion qui contient assez d'informations pour se connecter à un serveur. La chaîne de connexion ne doit pas utiliser les mots clés de chaîne de connexion suivants : Integrated Security = true, UserId, ou Password ; ou ContextConnection = true.

credential
SqlCredential

Objet SqlCredential.

newPasswordnewSecurePassword
SecureString

Nouveau mot de passe.newPassword doit être en lecture seule. Le mot de passe doit également se conformer à la stratégie de sécurité par mot de passe éventuellement définie sur le serveur, notamment la longueur minimale, les exigences en termes de caractères spécifiques, etc.

Exceptions

La chaîne de connexion contient n'importe quelle combinaison d'UserId, de Password, ou de Integrated Security=true.

- ou -

La chaîne de connexion contient Context Connection=true.

- ou -

newSecurePassword (ou newPassword) dépasse 128 caractères.

- ou -

newSecurePassword (ou newPassword) n’est pas en lecture seule.

- ou -

newSecurePassword (ou newPassword) est une chaîne vide.

L’un des paramètres (connectionString, credential ou newSecurePassword) a la valeur Null.

Voir aussi

S’applique à