Georg Moser
Georg Moser

Reputation: 706

Micronaut Http Basic Auth Prompt

I have been looking for a way to tell Micronaut (1.3.5) to add the "WWW-Authenticate" Header in case the authentication failed in a http basic auth setup. Per default this header is missing and only the status code 401 is returned.

Upvotes: 1

Views: 402

Answers (1)

Georg Moser
Georg Moser

Reputation: 706

The answer is to provide a custom ExceptionHandler like follows:


/**
 * AuthorizationException Handler, which adds header for showing browser basic auth dialogue.
 */
@Singleton
@Primary
public class HttpBasicAuthorizationExceptionHandler
        implements ExceptionHandler<AuthorizationException, MutableHttpResponse<?>> {


    @Override
    public MutableHttpResponse<?> handle(HttpRequest request, AuthorizationException exception) {
        return Flowable.fromPublisher(reject(exception.isForbidden())).blockingFirst();
    }

    /**
     * @param forbidden true if the status is HttpStatus.FORBIDDEN, HttpStatus.UNAUTHORIZED otherwise.
     * @return the http response.
     */
    private Publisher<MutableHttpResponse<?>> reject(boolean forbidden) {
        if (forbidden) {
            return Publishers.just(HttpResponse.status(HttpStatus.FORBIDDEN));
        }
        return Publishers.just(
                HttpResponse.status(HttpStatus.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, "Basic")
        );
    }

}

Upvotes: 1

Related Questions