如何使用scala重定向播放框架中的请求? [英] How to redirect request in play framework with scala?

查看:46
本文介绍了如何使用scala重定向播放框架中的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是播放框架 2.5.在我的应用程序中,我想拦截每个请求以检查该请求的会话中是否存在任何用户.如果用户不存在,则请求重定向到登录页面.所以,我的问题是如何在我的应用程序中实现它?

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 ?

在此先非常感谢您.

推荐答案

检查合适的用户后

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)
}

您会注意到,在我的情况下,我返回了 Unauthorized,但您可以轻松地将其替换为您正在寻找的重定向.

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

这篇关于如何使用scala重定向播放框架中的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆