Search code examples
scalahttpkerberos

How to do http requests with kerberos authentification?


I'm struggling to find a way to do an http request in scala, with kerberos authentification.

My curl request here :

curl --negotiate -u id:'password' -H "Content-Type: application/json;charset=UTF-8" 'http://website:port'

works fine, but I cant make it work with scala. So far, I have this :

    import java.net.{HttpURLConnection, URL}

    val urlString = "website"
    val url = new URL(urlString)
    val username = "id"
    val password = "password"

    // Open a connection to the URL
    val connection = url.openConnection().asInstanceOf[HttpURLConnection]

    // Set the authentication properties
    connection.setRequestProperty("Authorization", "Negotiate")
    connection.setRequestProperty("X-JavaNet-Auth-User", username)
    connection.setRequestProperty("X-JavaNet-Auth-Password", password)

    // Set other connection properties as needed (e.g. timeouts)
    connection.setConnectTimeout(5000)
    connection.setReadTimeout(5000)

    // Perform the request and read the response
    val responseCode = connection.getResponseCode()
    val inputStream = if (responseCode < 400) connection.getInputStream() else connection.getErrorStream()
    val response = scala.io.Source.fromInputStream(inputStream).mkString

    // Clean up the connection
    connection.disconnect()

But I get a 403 error, which I guess is linked to the kerbaros auth not working. What to do ? Maybe another library ?


Solution

  • A solution (that is not optimal but still works) was to add the kerberos keytab by running the correspond command in the terminal using import sys.process._ :

    import sys.process._
    "kinit -kt /path/to/keytab/keytab.keytab username"!
    

    The reason is that even if the kerberos keytab is already added in the session in which you run your script, you have to add it again because the code seems to run in a subsession of your session, which do not have access to the token.