How to add unauthorized WWW-Authenticate field to response header using Micronaut Security?

540 Views Asked by At

Using Micronaut Security, I would like the application to respond to a unauthorized request with a WWW-Authenticate header field for basic authentication, like this:

WWW-Authenticate: Basic realm="User Visible Realm"

Is it possible to do this inside the configuration file (ie. application.yaml)? If not, how would you recommend doing this with minimum boilerplate?

My current security configuration:

security:
  intercept-url-map:
    - pattern: /**/*
      access:
        - isAuthenticated()
  redirect:
    forbidden:
      enabled: false
    unauthorized:
      enabled: false

Thanks!

1

There are 1 best solutions below

0
On

I don't know that this is possible via configuration.

One way to achieve this is a server filter. The code below is groovy.


@Filter("/**")
class AuthenticateHeaderFilter extends OncePerRequestHttpServerFilter {

    @Override
    protected Publisher<MutableHttpResponse<?>> doFilterOnce(HttpRequest<?> request, ServerFilterChain chain) {
        return Publishers.map(chain.proceed(request)) { response ->
            if (response.status() == HttpStatus.UNAUTHORIZED) {
                response.header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"my realm\"")
            }
            return response
        }
    }

    @Override
    int getOrder() {
        return Integer.MIN_VALUE
    }
}