有人可以帮我修改发起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
拨打同样的电话,并且在那里工作。
有什么建议吗?
答案 0 :(得分:3)
Lift的创建者在old thread中建议了以下内容:
会话在HTTP请求/响应中很早就没有初始化 周期。但是,RequestVars是。我的建议是将用户放入 RequestVar然后在您的API模块中,读取RequestVar并将其放入 一个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
}
}
}
}