我一直在寻找一种方法来告诉Micronaut(1.3.5)添加“ WWW-Authenticate”标头,以防HTTP基本身份验证设置中的身份验证失败。 默认情况下,缺少此标头,仅返回状态码401。
答案 0 :(得分:1)
答案是提供一个自定义ExceptionHandler,如下所示:
/**
* 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")
);
}
}