Microsoft Entra 認証を使用して接続する

JDBC ドライバーのダウンロード

この記事には、Microsoft JDBC Driver for SQL Server で Microsoft Entra 認証機能を使用する Java アプリケーションの開発方法に関する情報が記載されています。

Microsoft Entra 認証を使用できます。これは、Microsoft Entra ID の ID を使用して Azure SQL データベース、Azure SQL Managed Instance、および Azure Synapse Analytics に接続するためのメカニズムです。 Microsoft Entra 認証は、データベース ユーザーの ID を一元管理するために、SQL Server 認証の代替として使用します。 JDBC ドライバーは、Microsoft Entra の認証情報を JDBC 接続文字列の中で指定して Azure SQL に接続することができます。 Microsoft Entra 認証を構成する方法については、「Microsoft Entra 認証を使用した Azure SQL への接続」を参照してください。

Microsoft JDBC Driver for SQL Server で Microsoft Entra 認証をサポートする接続プロパティは次のとおりです。

  • 認証: このプロパティを使用して、接続に使用する SQL 認証方法を指定します。 使用できる値:
    • ActiveDirectoryManagedIdentity

      • ドライバー バージョン v8.3.1 以降では、authentication=ActiveDirectoryMSI を使用して、「ID」サポートが有効になっている Azure リソースから Azure SQL データベース/Synapse Analytics に接続できます。 必要に応じて、この認証モードと共に、Connection または DataSource プロパティで msiClientId を指定できます。 msiClientId には、接続を確立するための accessToken を取得するために使用される、マネージド ID のクライアント ID が含まれている必要があります。 ドライバー バージョン v12.2 以降では、authentication=ActiveDirectoryManagedIdentity を使用して、「ID」サポートが有効になっている Azure リソースから Azure SQL データベース/Synapse Analytics に接続することもできます。 必要に応じて、user プロパティでマネージド ID のクライアント ID を設定することもできます。 詳細については、「ActiveDirectoryManagedIdentity 認証モードを使用して接続する」を参照してください。
    • ActiveDirectoryDefault

      • ドライバー バージョン v12.2 以降では、authentication=ActiveDirectoryDefault を使用して、Azure Identity クライアント ライブラリ内の DefaultAzureCredential 経由で Azure SQL/Synapse Analytics に接続できます。 詳細については、「ActiveDirectoryDefault 認証モードを使用して接続する」を参照してください。
    • ActiveDirectoryIntegrated

      • ドライバー バージョン v6.0 以降の場合、authentication=ActiveDirectoryIntegrated を使用して、統合認証を介して Azure SQL/Synapse Analytics に接続できます。 この認証モードを使用するには、オンプレミスの Active Directory フェデレーション サービス (AD FS) フェデレーション サービス (ADFS) をクラウドの Microsoft Entra ID とフェデレーションする必要があります。 設定が完了したら、Windows のアプリケーション クラス パスにネイティブ ライブラリ mssql-jdbc_auth-<version>-<arch>.dll を追加するか、クロスプラットフォーム認証サポートのために Kerberos チケットを設定すると、接続が可能になります。 ドメイン参加済みのマシンにログインしているときに、認証情報の入力を求められることなく、Azure SQL/Azure Synapse Analytics にアクセスできます。 詳細については、「ActiveDirectoryIntegrated 認証モードを使用して接続する」を参照してください。
    • ActiveDirectoryPassword

      • ドライバー バージョン v6.0 以降の場合、authentication=ActiveDirectoryPassword を使用して、Microsoft Entra のユーザー名とパスワードで Azure SQL/Synapse Analytics に接続できます。 詳細については、「ActiveDirectoryPassword 認証モードを使用して接続する」を参照してください。
    • ActiveDirectoryInteractive

      • ドライバー バージョン 9.2 以降の場合、authentication=ActiveDirectoryInteractive を使用して、対話型認証フロー (多要素認証) を介して Azure SQL/Synapse Analytics に接続できます。 詳細については、「ActiveDirectoryInteractive 認証モードを使用して接続する」を参照してください。
    • ActiveDirectoryServicePrincipal

      • ドライバー バージョン 9.2 以降の場合、authentication=ActiveDirectoryServicePrincipal を使用して、userName プロパティ内でアプリケーション/クライアント ID を指定し、パスワード プロパティ内でサービス プリンシパル ID のシークレットを指定することで、Azure SQL/Synapse Analytics に接続できます。 詳細については、「ActiveDirectoryServicePrincipal 認証モードを使用して接続する」を参照してください。
    • ActiveDirectoryServicePrincipalCertificate

      • ドライバー バージョン v12.4 以降の場合、authentication=ActiveDirectoryServicePrincipalCertificate を使用して、userName プロパティ内でアプリケーション/クライアント ID を指定し、clientCertificate プロパティ内でサービス プリンシパル証明書の場所を指定することで、Azure SQL データベース/Synapse Analytics に接続できます。 詳細については、「ActiveDirectoryServicePrincipalCertificate 認証モードを使用して接続する」を参照してください。
    • SqlPassword

      • authentication=SqlPassword を使用し、userName または user および password プロパティを使って SQL Server に接続します。
    • NotSpecified

      • これらの認証方法が不要な場合は、authentication=NotSpecified を使用するか、既定値のままにしておきます。
    • accessToken: この接続プロパティを使用し、アクセス トークンで SQL Database に接続します。 accessToken は、DriverManager クラス内の getConnection() メソッドの Properties パラメーターを使用してのみ設定できます。 接続 URL では使用できません。

詳細については、「接続プロパティの設定」ページの認証プロパティを参照してください。

クライアント設定の要件

基本的なドライバー のシステム要件に加えて、次の認証モードにはより多くの要件があります。

次の表に、各認証モードとドライバーのバージョンに必要なライブラリの依存関係を示します。 依存関係の依存関係も必要です。

認証オプション ドライバー バージョン ライブラリの依存ファイル
ActiveDirectoryPassword
ActiveDirectoryIntegrated
6.0 Adal4j 1.3.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
6.2.2~6.4 Adal4j 1.4.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
7.0 Adal4j 1.6.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
7.2 Adal4j 1.6.3
Client-Runtime-for-AutoRest 1.6.5
ActiveDirectoryPassword
ActiveDirectoryIntegrated
7.4~8.2 Adal4jl4j 1.6.4
Client-Runtime-for-AutoRest 1.7.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
8.4 Adal4j 1.6.5
Client-Runtime-for-AutoRest 1.7.4
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
9.2 msal4j 1.7.1
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
9.4 msal4j 1.10.1
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
10.2 msal4j 1.11.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
11.2 msal4j 1.11.3
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
12.2 msal4j 1.13.3
ActiveDirectoryManagedIdentity
ActiveDirectoryMSI
12.2 azure-identity 1.7.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
12.4 msal4j 1.13.8
ActiveDirectoryManagedIdentity
ActiveDirectoryMSI
12.4 azure-identity 1.9.0
ActiveDirectoryPassword
ActiveDirectoryIntegrated
ActiveDirectoryInteractive
ActiveDirectoryServicePrincipal
12.6 msal4j 1.14.1
ActiveDirectoryManagedIdentity
ActiveDirectoryMSI
12.6 azure-identity 1.11.1

ActiveDirectoryManagedIdentity 認証モードを使用して接続する

この認証モードは、バージョン 7.2 以降でサポートされています。 これを使用するには、次のように指定します authentication=ActiveDirectoryMSI。 バージョン 12.2 以降では、 authentication=ActiveDirectoryManagedIdentity 指定することもできます。

クライアント セットアップ要件に記載されているライブラリ依存関係の要件に加えて、この機能には次の要件があります。

次の例では、authentication=ActiveDirectoryManagedIdentity モードの使用方法を示します。 マネージド ID 用に構成された Azure リソース内からこの例を実行します。

例を実行するには、以下の行のサーバー/データベースの名前を、ご利用のサーバー/データベースの名前に置き換えます。

ds.setServerName("msentra-managed-demo.database.windows.net"); // replace 'msentra-managed-demo' with your server name
ds.setDatabaseName("demo"); // replace with your database name
//Optional
ds.setMSIClientId("94de34e9-8e8c-470a-96df-08110924b814"); // Replace with Client ID of user-assigned managed identity to be used

ActiveDirectoryMSI 認証モードを使用する例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MsEntraMSI {
    public static void main(String[] args) throws Exception {

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database name
        ds.setAuthentication("ActiveDirectoryMSI");
        // Optional
        ds.setMSIClientId("94de34e9-8e8c-470a-96df-08110924b814"); // Replace with Client ID of user-assigned managed identity to be used

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

次の例は、authentication=ActiveDirectoryManagedIdentity モードの使用方法を示しています。

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MSEntraManagedIdentity {
    public static void main(String[] args) throws Exception {

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database name
        ds.setAuthentication("ActiveDirectoryManagedIdentity"); // ActiveDirectoryManagedIdentity for JDBC driver version v12.2.0+
        // Optional
        ds.setUser("94de34e9-8e8c-470a-96df-08110924b814"); // Replace with Client ID of User-Assigned Managed Identity to be used

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

Azure Virtual Machine のこれらの例では、「システム割り当てマネージド ID」または「ユーザー割り当てマネージド ID」(msiClientId または user がマネージド ID のクライアント ID で指定されている場合) からアクセス トークンがフェッチされ、フェッチされたアクセス トークンを使用して接続が確立されます。 接続が確立された場合は、次のメッセージが表示されるはずです。

You have successfully logged on as: <your Managed Identity username>

ActiveDirectoryDefault 認証モードを使用して接続する

ActiveDirectoryDefault 認証オプションでは、Azure ID クライアント ライブラリの DefaultAzureCredential チェーン TokenCredential 実装が使用されます。 資格情報では一般的に使用される認証方法を連結して結合します。

ActiveDirectoryDefault 認証には、マネージド ID 用の Azure Identity クライアント ライブラリへの実行時の依存関係が必要です。 ライブラリのバージョンの詳細については、「クライアントのセットアップ要件」を参照してください。

次の表に、各 JDBC ドライバー バージョンの DefaultAzureCredential 資格情報チェーンを示します。

ドライバー バージョン azure-identity バージョンのドキュメント DefaultAzureCredential チェーン
12.2 azure-identity 1.7.0 環境
マネージド ID
IntelliJ
Azure CLI
Azure PowerShell
12.4 azure-identity 1.9.0 環境
ワークロード ID
マネージド ID
Azure Developer CLI
IntelliJ
Azure CLI
Azure PowerShell
12.6 azure-identity 1.11.1 環境
ワークロード ID
マネージド ID
Azure Developer CLI
IntelliJ
Azure CLI
Azure PowerShell

Environment 資格情報の構成に設定できる変数は多数あります。 DefaulAzureCredential 資格情報を含む Environment チェーンの構成の詳細については、前の表でリンクされている azure-identity ドキュメントの関連バージョンを参照してください。

Windows で IntellijCredential を使用するには、環境変数 INTELLIJ_KEEPASS_PATHkeepass ファイルの場所に設定します。 たとえば、INTELLIJ_KEEPASS_PATH=C:\user\your\path\to\the\keepass\file のようにします。

DefaultAzureCredential にさらに多くのテナントを指定するには、環境変数 ADDITIONALLY_ALLOWED_TENANTS を使用します。 この変数はコンマ区切りリストを受け入れます。 たとえば、ADDITIONALLY_ALLOWED_TENANTS=<your-tenant-id-0>,<your-tenant-id-1>,<your-tenant-id-2>,... のように指定します。

次の例では、authentication=ActiveDirectoryDefault 内で AzureCliCredentialDefaultAzureCredential モードを使用する方法を示します。

  1. 最初に、次のコマンドを使用して Azure CLI にサインインします。

    az login
    
  2. Azure CLI へのログインに成功したら、以下のコードを実行します。

    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
    
    public class MSEntraDefault {
        public static void main(String[] args) throws Exception {
    
            SQLServerDataSource ds = new SQLServerDataSource();
            ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
            ds.setDatabaseName("demo"); // Replace with your database name
            ds.setAuthentication("ActiveDirectoryDefault");
    
            try (Connection connection = ds.getConnection();
                    Statement stmt = connection.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
                if (rs.next()) {
                    System.out.println("You have successfully logged on as: " + rs.getString(1));
                }
            }
        }
    }
    

ActiveDirectoryIntegrated 認証モードを使用して接続する

Microsoft JDBC Driver for SQL Server で ActiveDirectoryIntegrated 認証を使用するには、次の 2 つの方法があります。

クライアントのセットアップ要件に依存するライブラリが必要であることを確認します。

次の例では、authentication=ActiveDirectoryIntegrated モードの使用方法を示します。 Microsoft Entra ID とフェデレーションされているドメイン参加済みのコンピューターで、この例を実行します。 ご自身の Windows ユーザーを表すデータベース ユーザーがデータベース内に存在している必要があり、CONNECT アクセス許可を持っている必要があります。

例を実行する前に、以下の行のサーバーとデータベースの名前を、ご利用のサーバーとデータベースの名前に置き換えます。

ds.setServerName("msentra-managed-demo.database.windows.net"); // replace 'msentra-managed-demo' with your server name
ds.setDatabaseName("demo"); // replace with your database name

ActiveDirectoryIntegrated 認証モードを使用する例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MSEntraIntegrated {
    public static void main(String[] args) throws Exception {

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database name
        ds.setAuthentication("ActiveDirectoryIntegrated");

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

この例を実行すると、Kerberos チケットが自動的に使用され、パスワードは必要ありません。 接続が確立された場合は、次のメッセージが表示されるはずです。

You have successfully logged on as: <your domain user name>

Windows、Linux、macOS で Kerberos チケットを設定する

現在のユーザーを Windows ドメイン アカウントにリンクするには、Kerberos チケットを設定する必要があります。 必要な手順の概要を次に示します。

Windows

Note

Windows では、これらの Kerberos 構成手順の代わりに、ダウンロードされたパッケージ内の mssql-jdbc_auth-<version>-<arch>.dll を使用できます。 これらの手順は、DLL を使用できない場合にのみ必要です。

JDK には kinit が付属しています。これを使用して、Microsoft Entra ID とフェデレーションされているドメイン参加済みのコンピューター上のキー配布センター (KDC) から TGT を取得することができます。

手順 1:チケット保証チケットの取得
  • 実行対象:Windows

  • アクション:

    • コマンド kinit username@DOMAIN.COMPANY.COM を使用して KDC から TGT を取得します。これによりドメイン パスワードの入力を求めるメッセージが表示されます。
    • klist を使用して、利用可能なチケットを確認します。 kinit が正常に実行された場合は、krbtgt/DOMAIN.COMPANY.COM@ DOMAIN.COMPANY.COM のチケットが表示されます。

    Note

    アプリケーションで KDC を検索する場合は、-Djava.security.krb5.conf での .ini ファイルの指定が必要になる場合があります。

Linux と macOS

必要条件

Kerberos ドメイン コントローラーのクエリを実行するための、Windows ドメインに参加しているコンピューターへのアクセス権。

手順 1:Kerberos KDC を検索する
  • 実行対象:Windows コマンド ライン

  • アクション: nltest /dsgetdc:DOMAIN.COMPANY.COM (DOMAIN.COMPANY.COM がドメインの名前にマップする場所)

  • サンプル出力

    DC: \\co1-red-dc-33.domain.company.com
    Address: \\2111:4444:2111:33:1111:ecff:ffff:3333
    ...
    The command completed successfully
    
  • 抽出される情報: DC 名。この場合は co1-red-dc-33.domain.company.com

手順 2:krb5.conf での KDC の構成
  • 実行対象:Linux/macOS

  • アクション: 任意のエディターで /etc/krb5.conf を編集します。 次のキーを構成します。

    [libdefaults]
      default_realm = DOMAIN.COMPANY.COM
    
    [realms]
    DOMAIN.COMPANY.COM = {
       kdc = co1-red-dc-28.domain.company.com
    }
    

    krb5.conf ファイルを保存して終了します。

    Note

    ドメインはすべて大文字にする必要があります。

手順 3: チケット保証チケットの取得をテストする
  • 実行対象:Linux/macOS
  • アクション:
    • コマンド kinit username@DOMAIN.COMPANY.COM を使用して KDC から TGT を取得します。これによりドメイン パスワードの入力を求めるメッセージが表示されます。
    • klist を使用して、利用可能なチケットを確認します。 kinit が正常に実行された場合は、krbtgt/DOMAIN.COMPANY.COM@ DOMAIN.COMPANY.COM のチケットが表示されます。

ActiveDirectoryPassword 認証モードを使用して接続する

次の例では、authentication=ActiveDirectoryPassword モードの使用方法を示します。

例をビルドして実行するには:

  1. クライアントのセットアップ要件に依存するライブラリが必要であることを確認します。

  2. 次のコード行を見つけて、サーバーとデータベースの名前を、実際のサーバーとデータベースの名前に置き換えます。

    ds.setServerName("msentra-managed-demo.database.windows.net"); // replace 'msentra-managed-demo' with your server name
    ds.setDatabaseName("demo"); // replace with your database name
    
  3. 次のコード行を見つけます。 ユーザー名を、接続に使用する Microsoft Entra ユーザーの名前に置き換えます。

    ds.setUser("bob@example.com"); // replace with your user name
    ds.setPassword("password");     // replace with your password
    

ActiveDirectoryPassword 認証モードを使用する例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MSEntraUserPassword {

    public static void main(String[] args) throws Exception{

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database
        ds.setUser("bob@example.com"); // Replace with your user name
        ds.setPassword("password"); // Replace with your password
        ds.setAuthentication("ActiveDirectoryPassword");

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

接続が確立された場合、出力として次のメッセージが表示されます。

You have successfully logged on as: <your user name>

ActiveDirectoryInteractive 認証モードを使用して接続する

次の例では、authentication=ActiveDirectoryInteractive モードの使用方法を示します。

例をビルドして実行するには:

  1. クライアントのセットアップ要件に依存するライブラリが必要であることを確認します。

  2. 次のコード行を見つけて、サーバーとデータベースの名前を、実際のサーバーとデータベースの名前に置き換えます。

    ds.setServerName("msentra-managed-demo.database.windows.net"); // replace 'msentra-managed-demo' with your server name
    ds.setDatabaseName("demo"); // replace with your database name
    
  3. 次のコード行を見つけます。 ユーザー名を、接続に使用する Microsoft Entra ユーザーの名前に置き換えます。

    ds.setUser("bob@example.com"); // replace with your user name
    

ActiveDirectoryInteractive 認証モードを使用する例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MSEntraInteractive {
    public static void main(String[] args) throws Exception{

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database
        ds.setAuthentication("ActiveDirectoryInteractive");

        // Optional login hint
        ds.setUser("bob@example.com"); // Replace with your user name

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

プログラムを実行すると、ユーザーの認証を行うためにブラウザーが表示されます。 正確にどのような内容が表示されるかは、ご自身の Microsoft Entra ID がどのように構成されているかによって決まります。 これにはユーザー名、パスワード、PIN、または電話による 2 番目のデバイス認証に対する多要素認証のプロンプトが含まれる場合があれば、含まれない場合もあります。 複数の対話型認証要求が同じプログラム内で行われ、認証ライブラリが以前にキャッシュされた認証トークンを再利用できる場合は、後の要求でプロンプトが表示されない場合もあります。

多要素認証を要求するように Microsoft Entra ID を構成する方法については、「クラウドにおける Microsoft Entra 多要素認証の開始方法」をご覧ください。

これらのダイアログ ボックスのスクリーンショットについては、「Microsoft Entra の多要素認証の使用」をご覧ください。

ユーザー認証が正常に完了した場合、ブラウザーに次のメッセージが表示されます。

Authentication complete. You can close the browser and return to the application.

このメッセージはユーザーの認証が成功したことだけを示しており、サーバーへの接続が成功したとは限らないことにご注意ください。 アプリケーションに戻った時点で、サーバーへの接続が確立されていると、次のメッセージが出力として表示されます。

You have successfully logged on as: <your user name>

ActiveDirectoryServicePrincipal 認証モードを使用して接続する

次の例では、authentication=ActiveDirectoryServicePrincipal モードの使用方法を示します。

例をビルドして実行するには:

  1. クライアントのセットアップ要件に依存するライブラリが必要であることを確認します。

  2. 次のコード行を見つけて、サーバーとデータベースの名前を、実際のサーバーとデータベースの名前に置き換えます。

    ds.setServerName("msentra-managed-demo.database.windows.net"); // replace 'msentra-managed-demo' with your server name
    ds.setDatabaseName("demo"); // replace with your database name
    
  3. 次のコード行を見つけます。 principalId の値を、接続に使用する Microsoft Entra サービス プリンシパルのアプリケーション ID/クライアント ID に置き換えます。 principalSecret の値はシークレットに置き換えます。

    String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your Microsoft Entra service principal ID.
    String principalSecret = "..."; // Replace with your Microsoft Entra principal secret.
    
  4. バージョン 10.2 以上の場合は setUser および setPassword、バージョン 9.4 以前の場合は setAADSecurePrincipalId および setAADSecurePrincipalSecret を使用して、プリンシパル ID とプリンシパル シークレットを設定します。

ActiveDirectoryServicePrincipal 認証モードを使用する例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MSEntraServicePrincipal {
    public static void main(String[] args) throws Exception{
        String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your Microsoft Entra service principal ID.
        String principalSecret = "..."; // Replace with your Microsoft Entra principal secret.

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database
        ds.setAuthentication("ActiveDirectoryServicePrincipal");
        ds.setUser(principalId); // setAADSecurePrincipalId for JDBC Driver 9.4 and below
        ds.setPassword(principalSecret); // setAADSecurePrincipalSecret for JDBC Driver 9.4 and below 

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

接続が確立された場合、出力として次のメッセージが表示されるはずです。

You have successfully logged on as: <your app/client ID>

ActiveDirectoryServicePrincipalCertificate 認証モードを使用して接続する

次の例では、authentication=ActiveDirectoryServicePrincipalCertificate モードの使用方法を示します。

例をビルドして実行するには:

  1. クライアントのセットアップ要件に依存するライブラリが必要であることを確認します。

  2. 次のコード行を見つけて、サーバーとデータベースの名前を、実際のサーバーとデータベースの名前に置き換えます。

    ds.setServerName("msentra-managed-demo.database.windows.net"); // replace 'msentra-managed-demo' with your server name
    ds.setDatabaseName("demo"); // replace with your database name
    
  3. 次のコード行を見つけます。 principalId の値を、接続に使用する Microsoft Entra サービス プリンシパルのアプリケーション ID/クライアント ID に置き換えます。 clientCertificate の値をサービス プリンシパル証明書の場所に置き換えます。

    String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your Microsoft Entra service principal ID.
    
    String clientCertificate = "..."; // Replace with the location for your Microsoft Entra service principal certificate.
    
  4. 上記の証明書にパスワードが必要な場合は、バージョン 10.2 以降で setPassword を使用するかまたはバージョン 9.4 以降で setAADSecurePrincipalSecret を使用してプリンシパル シークレットを設定します。

  5. 上記の証明書に秘密キーが関連付けられている場合は、setClientKey を使用して秘密キーを設定します。 このキーにパスワードが必要な場合は、setClientKeyPassword を使用して秘密キーのパスワードを設定します。

ActiveDirectoryServicePrincipalCertificate 認証モードを使用する例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class MSEntraServicePrincipalCertificate {
    public static void main(String[] args) throws Exception{
        String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your Microsoft Entra service principal ID.
        String clientCertificate = "..."; // Replace with the location of your service principal certificate.

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database
        ds.setAuthentication("ActiveDirectoryServicePrincipalCertificate");
        ds.setUser(principalId); // setAADSecurePrincipalId for JDBC Driver 9.4 and below
        ds.setClientCertificate(clientCertificate);

        try (Connection connection = ds.getConnection();
             Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

接続が確立された場合、出力として次のメッセージが表示されるはずです。

You have successfully logged on as: <your app/client ID>

アクセス トークンを使用して接続する

アプリケーションとサービスで、Microsoft Entra ID からアクセス トークンを取得し、それを使用して Azure SQL データベース、Azure SQL Managed Instance と Azure Synapse Analytics に接続することができます。

Note

accessToken は、DriverManager クラス内の getConnection() メソッドの Properties パラメーターを使用してのみ設定できます。 接続文字列では使用できません。 ドライバー バージョン v12.2 以降では、ユーザーは接続プール シナリオでのトークン更新のために、ドライバーに accessToken コールバックを実装して提供できます。 接続プールのシナリオでは、標準の JDBC 接続プール クラスを使用するために接続プールの実装が必要です。

次の例には、アクセス トークン ベースの認証を使用して、Azure に接続するシンプルな Java アプリケーションが含まれています。

例をビルドして実行するには:

  1. サービスの Microsoft Entra ID でアプリケーション アカウントを作成する

    1. Azure portal にサインインします。
    2. 左側のナビゲーション バーで Microsoft Entra ID に移動します。
    3. [アプリの登録] を選択します。
    4. [新規登録] を選択します。
    5. アプリケーションのフレンドリ名として mytokentest と入力します。
    6. アプリケーションを使用できるサポートされているアカウントの種類については、既定のままにします。
    7. 下部にある [登録] を選択します
    8. サインオン URL は必要ありません。何を指定しても構いません: 「https://mytokentest
    9. 下部にある Create を選択します。
    10. [登録] を選択すると、アプリがすぐに作成され、そのリソース ページに移動します。
    11. Essentials ボックスで、アプリケーション (クライアント) ID 値を検索し、コピーします。 この値は、後でご自身のアプリケーションを構成するのに必要です。
    12. ナビゲーション ウィンドウで、[証明書とシークレット] を選択します。 [クライアント シークレット (0)] タブで、[新しいクライアント シークレット] を選択します。 シークレットの説明を入力し、有効期限 (既定のままで構いません) を選択します。 下部にある [追加] を選択します。 重要 このページを離れる前に、生成されたクライアント シークレットの をコピーします。一度ページを離れると、後からこの値を表示することはできません。 この値がクライアント シークレットです。
    13. Microsoft Entra ID の [アプリの登録] ペインに戻り、[エンドポイント] タブを見つけます。OAuth 2.0 token endpoint の下のURLをコピーします。これが STS URL です。

    Azure Portal App Registration End Point - STS URL

  2. Microsoft Entra 管理者としてデータベースに接続し、T-SQL コマンドを使用して、アプリケーション プリンシパルの包含データベース ユーザーをプロビジョニングします。 Microsoft Entra 管理者と包含データベース ユーザーを作成する方法の詳細については、「Microsoft Entra 認証を使用した接続」を参照してください。

    CREATE USER [mytokentest] FROM EXTERNAL PROVIDER
    
  3. 例を実行するクライアント コンピューターに、Java 用 Microsoft Authentication Library (MSAL) ライブラリとその依存関係をダウンロードします。 MSAL は、この特定の例を実行するためにのみ必要です。 例ではこのライブラリの API を使用して、Microsoft Entra ID からアクセス トークンを取得します。 既にアクセス トークンがある場合は、この手順をスキップし、アクセス トークンを取得する例のセクションを削除できます。

次の例では、STS URL、クライアント ID、クライアント シークレット、サーバー、データベース名を実際の値に置き換えます。

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

// The microsoft-authentication-library-for-java is needed to retrieve the access token in this example.
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IClientCredential;

public class MSEntraTokenBased {

    public static void main(String[] args) throws Exception {

        // Retrieve the access token from Microsoft Entra ID.
        String spn = "https://database.windows.net/";
        String stsurl = "https://login.microsoftonline.com/..."; // Replace with your STS URL.
        String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.
        String clientSecret = "..."; // Replace with your client secret.

        String scope = spn +  "/.default";
        Set<String> scopes = new HashSet<>();
        scopes.add(scope);

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
        ConfidentialClientApplication clientApplication = ConfidentialClientApplication
            .builder(clientId, credential).executorService(executorService).authority(stsurl).build();
        CompletableFuture<IAuthenticationResult> future = clientApplication
            .acquireToken(ClientCredentialParameters.builder(scopes).build());

        IAuthenticationResult authenticationResult = future.get();
        String accessToken = authenticationResult.accessToken();

        System.out.println("Access Token: " + accessToken);

        // Connect with the access token.
        SQLServerDataSource ds = new SQLServerDataSource();

        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replace with your server name.
        ds.setDatabaseName("demo"); // Replace with your database name.
        ds.setAccessToken(accessToken);

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

接続に成功した場合は、出力として以下のメッセージが表示されるはずです。

Access Token: <your access token>
You have successfully logged on as: <your client ID>

アクセス トークン コールバックを使用して接続する

アクセス トークン プロパティと同様に、アクセス トークン コールバックを使用すると、ドライバーにアクセス トークンを指定する方法を登録できます。 プロパティに対するこのコールバックの利点は、コールバックで、トークンの有効期限が切れたときにドライバーによる新しいアクセス トークンの要求が許可されることです。 たとえば、新しい接続を作成する接続プールは、新しい有効期限を持つ新しいトークンを要求できます。 詳細については、「接続プールの使用」をご覧ください。

次の例では、accessToken コールバックの実装と設定を示します。

import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MSEntraAccessTokenCallback {

    public static void main(String[] args) {

        SQLServerAccessTokenCallback callback = new SQLServerAccessTokenCallback() {
            @Override
            public SqlAuthenticationToken getAccessToken(String spn, String stsurl) {

                String clientSecret = "..."; // Replace with your client secret.
                String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.

                String scope = spn + "/.default";
                Set<String> scopes = new HashSet<>();
                scopes.add(scope);

                try {
                    ExecutorService executorService = Executors.newSingleThreadExecutor();
                    IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
                    ConfidentialClientApplication clientApplication = ConfidentialClientApplication
                            .builder(clientId, credential).executorService(executorService).authority(stsurl).build();
                    CompletableFuture<IAuthenticationResult> future = clientApplication
                            .acquireToken(ClientCredentialParameters.builder(scopes).build());

                    IAuthenticationResult authenticationResult = future.get();
                    String accessToken = authenticationResult.accessToken();

                    return new SqlAuthenticationToken(accessToken, authenticationResult.expiresOnDate().getTime());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replaces with your server name.
        ds.setDatabaseName("demo"); // Replace with your database name.
        ds.setAccessTokenCallback(callback);

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

接続に成功した場合は、出力として以下のメッセージが表示されるはずです。

You have successfully logged on as: <your client ID>

バージョン 12.4 以降では、accessToken 接続文字列プロパティを使用して accessTokenCallbackClass コールバックを設定できます。 次の例は、このプロパティを使用して accessToken コールバックを設定する方法を示しています。

import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

 

public class MSEntraAccessTokenCallbackClass {
    public static class AccessTokenCallbackClass implements SQLServerAccessTokenCallback {
        @Override
        public SqlAuthenticationToken getAccessToken(String spn, String stsurl) {
            String clientSecret = "..."; // Replace with your client secret.
            String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.
            
            String scope = spn + "/.default";
            Set<String> scopes = new HashSet<>();
            scopes.add(scope);
            
            try {
                ExecutorService executorService = Executors.newSingleThreadExecutor();
                IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
                ConfidentialClientApplication clientApplication = ConfidentialClientApplication

                        .builder(clientId, credential).executorService(executorService).authority(stsurl).build();
                
                CompletableFuture<IAuthenticationResult> future = clientApplication
                        .acquireToken(ClientCredentialParameters.builder(scopes).build());
                
                IAuthenticationResult authenticationResult = future.get();
                String accessToken = authenticationResult.accessToken();
                
                return new SqlAuthenticationToken(accessToken, authenticationResult.expiresOnDate().getTime());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    public static void main(String[] args) throws Exception {
        
        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("msentra-managed-demo.database.windows.net"); // Replaces with your server name.
        ds.setDatabaseName("demo"); // Replace with your database name.
        ds.setAccessTokenCallbackClass(AccessTokenCallbackClass.class.getName());
        
        try (Connection connection = ds.getConnection();
             Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}

接続に成功した場合は、出力として以下のメッセージが表示されるはずです。

You have successfully logged on as: <your client ID>

次の手順

関連する概念の詳細については、次の記事を参照してください。