我正在使用以下代码在我的应用中使用HTTP Basic Auth 在未经授权的访问的情况下转换响应。它不是 工作。这里有什么不对?
// Http Basic Authentication
LiftRules.authentication = HttpBasicAuthentication("xxx") {
case (userName, userPass, _) => {
Console.println("Authenticating: " + userName)
User.find("userName", userName).map {
user =>
if (user.password.isMatch(userPass)) {
Account.authenticatedUser.setFieldsFromDBObject(user.asDBObject)
userRoles(AuthRole("authorisedUser"))
Console.println("Success: " + userName)
true
}
else {
Console.println("Failed: " + userName)
false
}
} openOr false
}
}
LiftRules.responseTransformers.append {
resp => resp match {
case UnauthorizedResponse("xxx") =>
Console.println("Responding modified...");
JsonUnauthorizedResponse(("error" -> "Incorrect username or password"))
case x => Console.println("Responding..."); x
}
}
我没有在RestApiHelper中获取修改后的URL响应 宾语。 有人可以指点我如何修改响应 在未经授权的情况下休息Api Urls。我不打算这样做 它使用状态代码。因为我正在创建一个供API使用的API 具有服务器控制的错误响应的移动应用程 很多其他因素。
解决方案更新: 以下基于CheatEx答案的重写案例类为我工作:
case class JsonHttpBasicAuthentication(realmName: String)(func: PartialFunction[(String, String, Req), Boolean]) extends HttpAuthentication {
def credentials(r: Req): Box[(String, String)] = {
header(r).flatMap(auth => {
val decoded = new String(Base64.decodeBase64(auth.substring(6, auth.length).getBytes)).split(":").toList
decoded match {
case userName :: password :: _ => Full((userName, password))
case userName :: Nil => Full((userName, ""))
case _ => Empty
}
}
)
}
override def realm = realmName
def verified_? = {
case (req) => {
credentials(req) match {
case Full((user, pwd)) if (func.isDefinedAt(user, pwd, req)) =>
func(user, pwd, req)
case _ => false
}
}
}
override def unauthorizedResponse: UnauthorizedResponse = new UnauthorizedResponse(realm) {
override def toResponse = {
val errResp: JValue = ("error" -> "Incorrect username or password")
InMemoryResponse(errResp.toString.getBytes("UTF-8"),
S.getHeaders(Nil), S.responseCookies, 200)
}
}
}
答案 0 :(得分:2)
我对Lift的默认未经授权的响应有同样的问题。我的解决方案是覆盖unauthorizedResponse
特征的HttpAuthentication
方法。
这是一个代码示例:
private object MyHttpAuth extends HttpAuthentication {
override def realm: String = "MyApp"
def verified_? : PartialFunction[Req, Boolean] = {
case req: Req => getUser(req) match {
case Some(userId) => {
userRoles(AuthRole(userId)::Nil)
true
}
case None => false
}
}
override def unauthorizedResponse: UnauthorizedResponse = new UnauthorizedResponse(realm) {
override def toResponse = InMemoryResponse(Array(), Nil, Nil, 401)
}
}