scala 如何使用kerberos认证来处理http请求?

goqiplq2  于 2023-04-06  发布在  Scala
关注(0)|答案(1)|浏览(169)

我正在努力寻找一种在scala中使用kerberos身份验证进行http请求的方法。
我的curl请求如下:

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

工作正常,但我不能让它与scala一起工作。到目前为止,我有这个:

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()

但是我得到了一个403错误,我猜这是链接到kerbaros auth不工作。怎么办?也许另一个库?

vc9ivgsu

vc9ivgsu1#

一个解决方案(虽然不是最佳的,但仍然有效)是通过在终端中使用import sys.process._运行相应的命令来添加kerberos keytab:

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

原因是,即使已经在运行脚本的会话中添加了kerberos keytab,您也必须再次添加它,因为代码似乎在会话的子会话中运行,而子会话没有访问令牌的权限。

相关问题