Is there a way to work around RatpackPac4j#require

2019-08-24 04:46发布

When testing Pac4j (2.x) authentication in the context of a Ratpack (1.5.x) app, I find that when I use this handler:

all RatpackPac4j.requireAuth(HeaderClient)

...Unauthorised requests get rejected correctly with a 401 status, and RFC-7235 states that a WWW-Authenticate header should be added, and it is not.

I raised an issue on the RatpackPac4j tracker here, but it was closed as (I infer) "won't fix" since Pac4j v3 implements this properly. And RatpackPac4j has not been upgraded to work with Pac4j v3 yet.

So: is it possible to insert something which post-process all responses to, for example, conditionally add a header based on the response?

Aside - I'm using the following versions in my gradle config:

    compile group: 'io.ratpack', name: 'ratpack-groovy', version: '1.5.4'
    compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
//    compile ratpack.dependency('pac4j') // Don't use this, because we need the org.pac4j version
    compile group: 'org.pac4j', name: 'ratpack-pac4j', version: '2.0.0'
    compile group: 'org.pac4j', name: 'pac4j-core', version: '2.2.1'
    compile group: 'org.pac4j', name: 'pac4j-jwt', version: '2.2.1'
    compile group: 'org.pac4j', name: 'pac4j-http', version: '2.2.1'

1条回答
Rolldiameter
2楼-- · 2019-08-24 04:58

Thanks to John Engelman in the Ratpack Slack channel, here is a work-around: use Response#beforeSend

handlers {
  all {
    response.beforeSend { response ->
      if (response.status.code == 401) {
        response.headers.set('WWW-Authenticate', 'bearer realm="authenticated api"')
      }
    }
  }
}

Note that this handler must be inserted before any others which may generate a 401 response or the callback will not be bound when they are triggered.

查看更多
登录 后发表回答