谁能帮我找回发起 REST 调用的经过身份验证的用户?我将 Lift 与 RestHelper 结合使用
在我的 Boot.scala
中,我有以下内容:
LiftRules.httpAuthProtectedResource.prepend {
case Req(List("api", "incomingCall", incomingCall), _, GetRequest) => Full(AuthRole("admin"))
}
LiftRules.authentication = HttpBasicAuthentication("lift") {
case (username, password, req) => {
User.find(By(User.firstName, username)) match {
case Full(user) if user.password.match_?(password) => {
userRoles(AuthRole("admin"))
User.logUserIn(user) //I tried with and without this line
true
}
case x => {
false
}
}
}
}
LiftRules.dispatch.append(IncomingCallRest)
我的 IncomingCallRest.scala 文件如下所示:
object IncomingCallRest extends RestHelper {
serve {
case "api" :: "incomingCall" :: incomingCall :: _ JsonGet _ => {
val currentUser = User.currentUser openOr User; //<--- On this line I'm trying to access the User, but it returns a blank user
val messageWithUser = (incomingCall, currentUser.userIdAsString)
ChatServer ! messageWithUser
JString(incomingCall)
}
}
}
User.currentUser
不返回经过身份验证的用户。
如您所见,我的代码基于 ChatServer example .我正在从 ChatIn.scala 对 User.currentUser
进行同样的调用,它在那里工作。
有什么建议吗?
最佳答案
Lift 的创建者在 old thread 中提出了以下建议:
Sessions are not initialized this early in the HTTP request/response cycle. However, RequestVars are. My suggestion is to put User into a RequestVar and then in your API module, read the RequestVar and put it into a SessionVar.
我按如下方式更改了我的代码以实现他的建议:
//IncomingCallRest.scala
object userIdRequestVar extends RequestVar[String]("Default") //This RequestVar is set in Boot.scala
object IncomingCallRest extends RestHelper {
serve {
case "api" :: "incomingCall" :: incomingCall :: _ JsonGet _ => {
val messageWithUser = (incomingCall, userIdRequestVar.is)
ChatServer ! messageWithUser
JString(incomingCall)
}
}
}
//Boot.scala
LiftRules.authentication = HttpBasicAuthentication("lift") {
case (username, password, req) => {
User.find(By(User.firstName, username)) match {
case Full(user) if user.password.match_?(password) => {
userRoles(AuthRole("admin"))
userIdRequestVar.set(user.userIdAsString) //Set the RequestVar
true
}
case x => {
false
}
}
}
}
关于http - 在 Lift RestHelper 中获取 currentUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6532180/