问题
I want to create an authentication route for my Lift Application.
- Create a route, for instance
www.myapp.com/user/login
- I am not using Lift forms/templating. The forms are rendered in JS.
- Send a post request with email and password.
- Call Lift authentication when that POST request is received.
- Use the
Users.login(email, password)
method to validate the credentials.
Q:
How do I tell Lift to authenticate the credentials incoming via /user/login
?
回答1:
This is overly simplistic, but something like this will allow you to create a url that you can post to. The JSON extraction is not very safe, but should give you an idea of how this might work.
In Boot.scala
LiftRules.dispatch.append(new RestHelper{
serve {
case JsonPost("user" :: "login" :: Nil, (json, _)) =>
//extract JSON from json object to get username and password
val userEmail:String = (json \ "username").extract[String]
val password = (json \ "password").extract[String]
User.login(userEmail, password) match {
case Full(r) =>
User.current(true)
InMemoryResponse(Array(), Nil, Nil, 200)
case _ => ForbiddenResponse
}
}
})
In User.scala
object User {
object loggedIn extends SessionVar[Boolean](false)
}
Then you can use if(User.loggedIn.get){ ... }
to test if the user is logged in anywhere. This will work for anything added to the stateful dispatch, if you use LiftRules.statelessDispatch
the session will not exist.
回答2:
I created a quick working example which you can checkout on github. It uses the code you provided, so hopefully it will be pretty straightforward. You can take a look here: https://github.com/jcern/lift_httpauth
But, essentially to add the code to the sitemap, you'd just need to add the following to Boot.scala
:
Menu("Login Required") / "user" / "login"
And make sure there is a user/login.html
in your webapp root.
来源:https://stackoverflow.com/questions/16640124/lift-authentication