http - 在 Lift RestHelper 中获取 currentUser

标签 http authentication scala lift

谁能帮我找回发起 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/

相关文章:

php - Laravel附加/自定义查询,用于验证用户

ruby-on-rails - 使用 API key 时如何跳过设计身份验证?

http - Ngrok net::ERR_CONTENT_LENGTH_MISMATCH 错误

http - "success, and thus you no longer have access"的 REST HTTP 状态代码

asp.net - 我可以在一个 Web 应用程序中跨多个服务使用身份验证吗?

windows - 强制关闭时的scala关闭钩子(Hook)

scala - @transient 惰性 val 字段序列化

scala - 无法将有序数据写入 Spark 中的 Parquet

c++ - InternetOpenUrl 仅在下载整个 HTTP 响应后返回

ios - 当手机磁盘空间不足时停止下载