Play Framework:如何为每个响应添加标题

时间:2015-06-09 10:47:29

标签: scala playframework http-headers token

在以下Controller中,Authenticated从请求标头中提取令牌,并且当且仅当令牌有效时才会调用给定的操作(为简洁起见,代码已经过简化):

object MyController extends Controller {

  def Authenticated(action: Token => EssentialAction) = EssentialAction { requestHeader =>
    val jwt = requestHeader.headers.get(HeaderNames.AUTHORIZATION) match {
      case Some(header) => s"""$AuthScheme (.*)""".r.unapplySeq(header).map(_.head.trim)
      case _ => requestHeader.getQueryString("auth").map(UriEncoding.decodePath(_, SC.US_ASCII.name))
    }

    jwt match {
      case Some(t) if t.isValid =>
        val token: Token = authService.token(t)
        action(token)(requestHeader)
      case _ => Done(Unauthorized.withHeaders(HeaderNames.WWW_AUTHENTICATE -> AuthScheme))
    }
  }

  def getUser(userId: String) = Authenticated { token =>
    Action.async { request =>
      userService.find(userId).map {
        case Some(user) => Ok(Json.obj("user" -> user.asJson)).withHeaders(
            "token" -> authService.renew(token).asJson.toString
          )
        case _ => NotFound
      }
    }
  }
}

authService.token(t)返回的令牌是JWT(JSON Web令牌),它只能使用一次......所以我需要在每次请求后返回一个新令牌。想法是将新令牌放在响应头中。也就是说,有没有办法在每个响应中添加token标头而不必在每个操作中调用withHeader

2 个答案:

答案 0 :(得分:6)

只需创建一个过滤器,然后在Global.scala中添加WithFilters类。

import play.api.mvc._

object Global extends WithFilters(TokenFilter) {
  ...
}

以下是用于记录的过滤器示例,因此您可以轻松更改以满足您的需求。

val loggingFilter = Filter { (next, rh) =>
  val start = System.currentTimeMillis

  def logTime(result: PlainResult): Result = {
    val time = System.currentTimeMillis - start
    Logger.info(s"${rh.method} ${rh.uri} took ${time}ms and returned ${result.header.status}")
    result.withHeaders("Request-Time" -> time.toString)
  }

  next(rh) match {
    case plain: PlainResult => logTime(plain)
    case async: AsyncResult => async.transform(logTime)
  }
}

答案 1 :(得分:1)

我会使用ActionComposition。在Java中它可能看起来像:

public class YourActionComposition extends Action<YourAnnotation> {

  @With(YourActionComposition.class)
  @Target({ ElementType.TYPE, ElementType.METHOD })
  @Retention(RetentionPolicy.RUNTIME)
  public @interface YourAnnotation {
  }

  public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    Promise<Result> call = delegate.call(ctx);
    // Add something to your headers here
    return call;
  }
}