Java – Azure SQL DB への ActiveDirectoryPassword を使った接続 No.10

自己投資としてチャレンジしている内容を Blog で公開しています。

今回は Azure SQL Database への ActiveDirectoryPassword 認証を使った接続方法について紹介します。

▼1. Azure SQL Database への 接続

Relational Database は色々な種類がありますが、今回 Microsoft が提供している Azure SQL Database へ接続する方法を案内します。
また SQL Database へ接続する方法は以下のとおり複数ありますが、この blog では ActiveDirectory – パスワードの認証を利用した接続方法を紹介します。

  • Windows 認証
  • SQL Server 認証
  • Azure Active Directory – MFA サポート付きユニバーサル
  • Azure Active Directory – パスワード
  • Azure Directory – 統合

▼2. ActiveDirectoryPassword を使った Azure SQL Database への 接続

2-1. SQL Server management Studio (SSMS) や sqlcmd を利用し SQL Server に接続後、ActiveDirectoryPassword 用のユーザーを作成し権限を付与します。

-- Create a user
CREATE USER [user@xxx.com] FROM EXTERNAL PROVIDER;
-- Add this user into db_owner group
EXEC sp_addrolemember db_owner,[user@xxx.com];

2-2. ActiveDirectoryPassword の認証を行うために必要なライブラリーをダウンロードし、IntelliJ の File – Project structure – Libraries でダウンロードした library を追加。
– adal4j
https://repo1.maven.org/maven2/com/microsoft/azure/adal4j/1.6.4/adal4j-1.6.4.jar
– oauth2-oidc-sdk
https://repo1.maven.org/maven2/com/nimbusds/oauth2-oidc-sdk/6.5/oauth2-oidc-sdk-6.5.jar
— gson
https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar
— json-smart
https://repo1.maven.org/maven2/net/minidev/json-smart/1.3.1/json-smart-1.3.1.jar
— nimbus-jose-jwt
https://repo1.maven.org/maven2/com/nimbusds/nimbus-jose-jwt/8.2.1/nimbus-jose-jwt-8.2.1.jar
— slf4j-api
https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar
— mssql-jdbc
https://repo1.maven.org/maven2/com/microsoft/sqlserver/mssql-jdbc/6.4.0.jre8/mssql-jdbc-6.4.0.jre8.jar

2-3. 以下は Azure SQL Database へ ActiveDirectoryPassword を使って接続し select を実行する例です。SQL Server名: sqlservertest , データベース名 testdb としています。t1 テーブルには (1,200) と (2, 200) の二つのレコードがあります。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.Date;
import com.microsoft.sqlserver.jdbc.*;

public class consqlwithadp {
    private static final Logger log = LoggerFactory.getLogger(consqlwithadp.class);

    public static void main(String[] args) throws InterruptedException {
        Connection con = null;
        boolean success = false;
        int retryc = 0;
        int max_retries = 3;
        ResultSet resultSet = null;
        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("sqlservertest.database.windows.net");
        ds.setDatabaseName("testdb");
        ds.setUser("user@xxx.com");
        ds.setPassword("Password");
        ds.setAuthentication("ActiveDirectoryPassword");
        ds.setEncrypt(true);
        while (!success && retryc < max_retries) {
            try (Connection connection=ds.getConnection();Statement stmt=connection.createStatement();ResultSet rs=stmt.executeQuery("select * from t1")){
                while (rs.next()){
                    System.out.println("You have successfully logged on as:" + rs.getString("c1") + "\t" + rs.getString("c2"));
                }
                success = true;
            } catch (SQLException se) {
                retryc++;
                System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
                log.error("Error Messages: {}, retry count is {}", se, retryc);
                // 30 seconds (30000 milliseconds) interval
                Thread.sleep(30000);
            }
        }
        try {
            if (con != null) {
                con.close();
                System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
                log.info("The connection is closed");
            }else{
                log.info("The connection was closed");
            }
        } catch (SQLException sec) {
            System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
            log.error("Error MEssages of fin ", sec);
        }
    }
}

2-4. 実行結果は以下となります。

20/06/22 12:36:35 INFO AuthenticationAuthority: [Correlation ID: xxxxxx] Instance discovery was successful
You have successfully logged on as:1    100
You have successfully logged on as:2    200
20/06/22 12:36:36 INFO consqlwithadp: The connection was closed


▼3. 参考情報

以上です。参考になりましたら幸いです。



コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です