gpt4 book ai didi

http - 部分应用程序的 Scalatra 基本身份验证

转载 作者:可可西里 更新时间:2023-11-01 16:56:36 26 4
gpt4 key购买 nike

我正在尝试弄清楚如何编写一个为某些 URL 启用基本身份验证的应用程序。经过身份验证的部分不应该有基于表单的身份验证,只有我可以从 Javascript/JQuery 轻松完成的默认登录。我见过 few examples这看起来很复杂,当我尝试使用它们时,很多东西都被弃用了,一般来说,现在要编译示例代码似乎需要做很多工作。

那么这些示例仍然是 Scalatra 必须提供的最好的示例,还是现在有更简单的方法?

我正在使用 Scalatra(带有 scalatra-auth)版本 2.1.1。

最佳答案

找到一个 easier example并使以下代码正常工作。

package mc.nulty

import org.scalatra.auth.strategy.BasicAuthStrategy.BasicAuthRequest
import org.scalatra._
import scalate.ScalateSupport

class McNultyServlet extends ScalatraServlet with ScalateSupport {

get("/") {
basicAuth
<html>
<body>
<h1>Hello, world!</h1>
Say <a href="hello-scalate">hello to Scalate</a>.
</body>
</html>
}

notFound {
// remove content type in case it was set through an action
contentType = null
// Try to render a ScalateTemplate if no route matched
findTemplate(requestPath) map { path =>
contentType = "text/html"
layoutTemplate(path)
} orElse serveStaticResource() getOrElse resourceNotFound()
}

protected def basicAuth() = {
val req = new BasicAuthRequest(request)

def notAuthenticated() {
response.setHeader("WWW-Authenticate", "Basic realm=\"%s\"" format "mc-nulty")
halt(401, "Unauthenticated")
}

if(!req.providesAuth) {
notAuthenticated
}
if(!req.isBasicAuth) {
halt(400, "Bad Request")
}
val user = DAO.validateLoginPassword(req.username, req.password)
if (user != null)
response.setHeader("REMOTE_USER", "user.id")
else {
notAuthenticated
}
Option(user)
}

object DAO {
def validateLoginPassword(username: String, password: String) : User = {
if (username.equals("foo")) new User()
else null
}
}
class User(val id:String = "dummyid") {}
}

关于http - 部分应用程序的 Scalatra 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14302868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com