How to redirect request in play framework with scala?

三世轮回 提交于 2019-12-08 03:42:02

问题


I am using play framework 2.5. In my application i want to intercept each request to check whether any user exists or not in session of that request. if user does not exists then request redirect to the login page. So, my question is how can i achieve it in my application ?

Thank You very much in advance.


回答1:


After you check for the appropriate user

Redirect(routes.Application.login())

I won't assume anything about your authentication strategy, but he're is a simple token-based authentication strategy I use when I want to intercept the user on each request.

object UserAuthenticator extends Controller {

  case class UserAuthenticatedRequest[A](user: User, authToken: String, request: Request[A]) extends WrappedRequest(request)

  def userAuthenticated[A](p: BodyParser[A])(f: UserAuthenticatedRequest[A] => Result) = {
    Action(p) { implicit request =>
      request.headers.get(AUTHORIZATION).map(_.split(" ")) match {
        case Some(Array(k, v)) if k == "auth-token" => findUserByAuthToken(v).map(user => f(UserAuthenticatedRequest(user, v, request))).getOrElse(Unauthorized)
        case _ => Unauthorized
      }
    }
  }

  def userAuthenticated(f: UserAuthenticatedRequest[AnyContent] => Result): Action[AnyContent] = {
    userAuthenticated(parse.anyContent)(f)
  }

Using the above, my controllers can do the following:

def myControllerMethod = userAuthenticated { request =>
  doSomethingWith(request.user)
}

You'll notice in my case I return Unauthorized, but you could easily replace that with the redirect you're looking for.



来源:https://stackoverflow.com/questions/36797048/how-to-redirect-request-in-play-framework-with-scala

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