SqlConnection.ChangePassword Metoda

Definicja

Przeciążenia

Nazwa Opis
ChangePassword(String, SqlCredential, SecureString)

Zmienia hasło programu SQL Server dla użytkownika wskazanego w obiekcie SqlCredential.

ChangePassword(String, String)

Zmienia hasło SQL Server dla użytkownika wskazanego w parametry połączenia do podanego nowego hasła.

ChangePassword(String, SqlCredential, SecureString)

Źródło:
SqlConnection.cs
Źródło:
SqlConnection.cs
Źródło:
SqlConnection.cs
Źródło:
SqlConnection.cs

Zmienia hasło programu SQL Server dla użytkownika wskazanego w obiekcie SqlCredential.

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

Parametry

connectionString
String

Parametry połączenia zawierające wystarczającą ilość informacji, aby nawiązać połączenie z serwerem. Connection string nie należy używać żadnego z następujących słów kluczowych parametry połączenia: Integrated Security = true, lub UserIdPassword ; lub ContextConnection = true.

credential
SqlCredential

Obiekt SqlCredential.

newSecurePasswordnewPassword
SecureString

Nowe hasło. newSecurePassword musi być tylko do odczytu. Hasło musi być również zgodne z wszelkimi zasadami zabezpieczeń haseł ustawionymi na serwerze (na przykład minimalną długość i wymagania dotyczące określonych znaków).

Wyjątki

  • Parametry połączenia zawierają dowolną kombinację UserId, Passwordlub Integrated Security=true.
  • newSecurePassword jest większy niż 128 znaków.
  • newSecurePassword nie jest tylko do odczytu.
  • newSecurePassword jest pustym ciągiem.

Jeden z parametrów (connectionString, credentiallub newSecurePassword) ma wartość null.

Dotyczy

ChangePassword(String, String)

Źródło:
SqlConnection.cs
Źródło:
SqlConnection.cs
Źródło:
SqlConnection.cs
Źródło:
SqlConnection.cs

Zmienia hasło SQL Server dla użytkownika wskazanego w parametry połączenia do podanego nowego hasła.

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)

Parametry

connectionString
String

Parametry połączenia zawierające wystarczającą ilość informacji, aby nawiązać połączenie z żądanym serwerem. Parametry połączenia muszą zawierać identyfikator użytkownika i bieżące hasło.

newPassword
String

Nowe hasło do ustawienia. To hasło musi być zgodne z wszelkimi zasadami zabezpieczeń haseł ustawionymi na serwerze, w tym minimalną długością, wymaganiami dotyczącymi określonych znaków itd.

Wyjątki

  • Parametry połączenia obejmują opcję używania zintegrowanych zabezpieczeń.
  • newPassword przekracza 128 znaków.

Parametr connectionString lub newPassword ma wartość null.

Przykłady

Poniżej przedstawiono prosty przykład zmiany hasła:

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

Poniższa aplikacja konsolowa demonstruje problemy związane ze zmianą hasła użytkownika, ponieważ bieżące hasło wygasło.

using System;
using System.Data;
using Microsoft.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;
    }
}

Uwagi

W przypadku korzystania z SQL Server na Windows Server deweloperzy mogą korzystać z funkcji, które umożliwiają aplikacji klienckiej podanie bieżącego i nowego hasła w celu zmiany istniejącego hasła. Aplikacje mogą implementować funkcje, takie jak monitowanie użytkownika o nowe hasło podczas początkowego logowania, jeśli stary wygasł, i tę operację można ukończyć bez interwencji administratora. Ta metoda zmienia hasło SQL Server dla użytkownika wskazanego w podanym connectionString parametrze na wartość podaną w parametrze newPassword . Jeśli parametry połączenia zawierają opcję zintegrowanych zabezpieczeń (czyli "Zintegrowane zabezpieczenia=True" lub równoważne), zgłaszany jest wyjątek. Aby określić, że hasło wygasło, wywołanie metody Open() zgłasza SqlException. Aby wskazać, że hasło zawarte w parametrach połączenia musi zostać zresetowane, właściwość Number dla wyjątku zawiera wartość stanu 18487 lub 18488. Pierwsza wartość (18487) wskazuje, że hasło wygasło, a drugi (18488) wskazuje, że hasło musi zostać zresetowane przed zalogowaniem. Ta metoda otwiera własne połączenie z serwerem, żąda zmiany hasła i zamyka połączenie natychmiast po zakończeniu. To połączenie nie jest pobierane ani zwracane do puli połączeń SQL Server.

Dotyczy