From 20e5e01c5d74d89314aafa887c03f46e66af44e6 Mon Sep 17 00:00:00 2001 From: ravikd744 Date: Thu, 13 Aug 2020 17:09:35 -0400 Subject: [PATCH] Create Scala Connector with Service Principal using MSAL.scala dependency jars required to be imported in databricks cluster: spark_mssql_connector_2_11_1_1_0.jar oauth2_oidc_sdk_7_4.jar slf4j_api_1_7_28.jar jackson_databind_2_10_1.jar lombok_1_18_6.jar json_smart_2_3.jar nimbus_jose_jwt_8_14_1.jar content_type_2_0.jar asm_5_0_4.jar accessors_smart_1_2.jar lang_tag_1_4_4.jar jcip_annotations_1_0_1.jar msal4j_1_6_1.jar --- ...or with Service Principal using MSAL.scala | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 samples/Scala Connector with Service Principal using MSAL.scala diff --git a/samples/Scala Connector with Service Principal using MSAL.scala b/samples/Scala Connector with Service Principal using MSAL.scala new file mode 100644 index 0000000..1a1a649 --- /dev/null +++ b/samples/Scala Connector with Service Principal using MSAL.scala @@ -0,0 +1,47 @@ +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.nimbusds.oauth2.sdk.http.HTTPResponse +import com.nimbusds.oauth2.sdk.id.ClientID + +import java.util.Collections + + +val dbname = "yourdbname" +val servername = "jdbc:sqlserver://yourazsqlserver.database.windows.net" +val tablename = "yourtablename" + + +val authority="https://login.microsoftonline.com/yourtenantid" +val clientId="clientidofyourserviceprincipal" +val secret="clientsecret" +val scope="https://database.windows.net/.default" + +val app = ConfidentialClientApplication.builder( + clientId, + ClientCredentialFactory.createFromSecret(secret)) + .authority(authority) + .build() +// With client credentials flows the scope is ALWAYS of the shape "resource/.default", as the +// application permissions need to be set statically (in the portal), and then granted by a tenant administrator +val clientCredentialParam = ClientCredentialParameters.builder( + Collections.singleton(scope)) + .build() + +val accessToken=app.acquireToken(clientCredentialParam).get().accessToken() + +val df = spark.read.format("com.microsoft.sqlserver.jdbc.spark") + .option("url",servername) + .option("dbtable",tablename) + .option("databaseName",dbname) + .option("accessToken",accessToken) + .option("connectTimeout",30) //seconds, allow extra time for paused DB to start-up + .option("queryTimeout",30) //seconds + .option("hostNameInCertificate","*.database.windows.net") + .option("trustServerCertificate","true") + .option("encrypt","true") + .load() +display(df) +