Share via


SqlConnection.ChangePassword 메서드

정의

오버로드

ChangePassword(String, SqlCredential, SecureString)

SqlCredential 개체에 지정된 사용자에 대한 SQL Server 암호를 변경합니다.

ChangePassword(String, String)

연결 문자열에 지정된 사용자의 SQL Server 암호를 제공된 새 암호로 변경합니다.

ChangePassword(String, SqlCredential, SecureString)

SqlCredential 개체에 지정된 사용자에 대한 SQL Server 암호를 변경합니다.

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)

매개 변수

connectionString
String

서버에 연결하는 데 충분한 정보가 포함된 연결 문자열입니다. 연결 문자열에서 Integrated Security = true, UserId, Password 또는 ContextConnection = true 연결 문자열 키워드 중 하나를 사용해서는 안 됩니다.

credential
SqlCredential

SqlCredential 개체입니다.

newSecurePasswordnewPassword
SecureString

새 암호입니다. newSecurePassword는 읽기 전용이어야 합니다. 암호는 서버에 설정된 최소 길이, 특정 문자 요구 사항 등의 암호 보안 정책도 따라야 합니다.

예외

연결 문자열에 UserId, Password 또는 Integrated Security=true의 조합이 있습니다.

또는

newSecurePassword가 128자보다 긴 경우

또는

newSecurePassword 은 읽기 전용이 아닙니다.

또는

newSecurePassword이 빈 문자열인 경우

매개 변수 중 하나(connectionString, credential, 또는 newSecurePassword)가 null입니다.

적용 대상

ChangePassword(String, String)

연결 문자열에 지정된 사용자의 SQL Server 암호를 제공된 새 암호로 변경합니다.

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)

매개 변수

connectionString
String

원하는 서버에 연결하는 데 충분한 정보가 포함된 연결 문자열입니다. 연결 문자열은 사용자 ID와 현재 암호를 포함해야 합니다.

newPassword
String

설정할 새 암호입니다. 이 암호는 서버에 설정된 최소 길이, 특정 문자 요구 사항 등의 암호 보안 정책을 따라야 합니다.

예외

연결 문자열에 통합 보안을 사용할 수 있는 옵션이 포함된 경우

Or

newPassword가 128자를 초과합니다.

connectionString 또는 newPassword 매개 변수가 null인 경우

예제

다음은 암호를 변경하는 간단한 예입니다.

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  

다음 콘솔 애플리케이션에서 사용자의 암호를 변경 하 여 현재 암호 만료 되었기 때문에 관련 된 문제를 보여 줍니다.

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;
    }
}

설명

SQL Server를 Windows Server에서 사용 하는 경우 개발자가 기존 암호를 변경 하려면 현재 및 새 암호를 제공 하는 클라이언트 애플리케이션을 수 있는 기능을 활용을 걸릴 수 있습니다. 애플리케이션은 이전 암호가 만료된 경우 초기 로그인 중에 사용자에게 새 암호를 묻는 메시지와 같은 기능을 구현할 수 있으며 관리자의 개입 없이 이 작업을 완료할 수 있습니다.

메서드는 ChangePassword 제공된 connectionString 매개 변수에 표시된 사용자의 SQL Server 암호를 매개 변수에 newPassword 제공된 값으로 변경합니다. 연결 문자열 통합 보안 옵션(즉, "통합 보안=True" 또는 해당)이 포함된 경우 예외가 throw됩니다.

암호가 만료되었는지 확인하려면 메서드를 호출하면 OpenSqlException발생합니다. 연결 문자열 내에 포함된 암호를 다시 Number 설정해야 함을 나타내기 위해 예외의 속성에는 상태 값 18487 또는 18488이 포함됩니다. 첫 번째 값(18487)은 암호가 만료되었음을 나타내고 두 번째 값(18488)은 로그인하기 전에 암호를 재설정해야 했음을 나타냅니다.

이 메서드는 서버에 대한 자체 연결을 열고, 암호 변경을 요청하고, 완료되는 즉시 연결을 닫습니다. 이 연결은 SQL Server 연결 풀에서 검색되거나 반환되지 않습니다.

적용 대상