Azure SQL and AAD Authentication

感情迁移 提交于 2021-02-11 08:45:42

问题


Is Azure SQL support access via AAD Client Id & Secret? If yes what would be the TSQL to give access to AAD ClientId and Can I use SSMS to connect to Azure SQL with AAD Client and secret?


回答1:


Yes you can use the Access token (AD Token)

Applications/services can retrieve an access token from the Azure Active Directory and use that to connect to SQL Azure Database.

  1. Provide anything(http://mytokentest) in signonURL as while Registering your APP

  2. CREATE USER [mytokentest] FROM EXTERNAL PROVIDER

Try the below code in Client App

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

        // Retrieve the access token from the AD.
        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.

        AuthenticationContext context = new AuthenticationContext(stsurl, false, Executors.newFixedThreadPool(1));
        ClientCredential cred = new ClientCredential(clientId, clientSecret);

        Future<AuthenticationResult> future = context.acquireToken(spn, cred, null);
        String accessToken = future.get().getAccessToken();

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

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

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

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

Follow here with Sample Java Code

  1. Register your application with Azure Active Directory and get the client id for your code.
  2. Create a database user representing the application. (Completed earlier in step 6.)
  3. Create a certificate on the client computer runs the application
  4. Add the certificate as a key for your application.

Follow here with Sample C# Code



来源:https://stackoverflow.com/questions/51707764/azure-sql-and-aad-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!