Skip to content
This repository was archived by the owner on Feb 27, 2025. It is now read-only.

Create Scala Connector with Service Principal using MSAL.scala #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions samples/Scala Connector with Service Principal using MSAL.scala
Original file line number Diff line number Diff line change
@@ -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)