Lift Authentication

我怕爱的太早我们不能终老 提交于 2019-12-08 05:55:24

问题


I want to create an authentication route for my Lift Application.

  1. Create a route, for instance www.myapp.com/user/login
  2. I am not using Lift forms/templating. The forms are rendered in JS.
  3. Send a post request with email and password.
  4. Call Lift authentication when that POST request is received.
  5. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!