You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Micronaut Security为未授权响应添加WWW-Authenticate头

回答

配置可行性说明

仅通过你当前给出的配置不能直接实现该功能,不过如果你的应用仅使用HTTP Basic作为唯一认证方式,仅需补充几行配置即可实现,无需编写代码。

方案1:纯配置实现(优先选用)

在你现有的application.yaml中补充Basic认证相关配置即可:

security:
  # 新增以下Basic认证配置
  basic:
    enabled: true
    realm-name: "User Visible Realm"
  # 原有配置保持不变
  intercept-url-map:
    - pattern: /**/*
      access:
        - isAuthenticated()
  redirect:
    forbidden:
      enabled: false
    unauthorized:
      enabled: false

配置生效后,未授权请求会自动返回你需要的WWW-Authenticate: Basic realm="User Visible Realm"响应头。

方案2:少量代码实现(适配多认证方式场景)

如果你的应用同时存在JWT、OAuth2等多种认证方式,纯配置方案不会自动返回Basic认证的响应头,此时只需添加一个自定义异常处理器即可,无多余样板代码:

import io.micronaut.context.annotation.Replaces;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Produces;
import io.micronaut.http.server.exceptions.ExceptionHandler;
import io.micronaut.security.authentication.AuthorizationExceptionHandler;
import io.micronaut.security.authentication.UnauthorizedException;
import jakarta.inject.Singleton;

@Singleton
@Replaces(AuthorizationExceptionHandler.class)
@Produces
public class CustomUnauthorizedHandler implements ExceptionHandler<UnauthorizedException, HttpResponse<?>> {
    @Override
    public HttpResponse<?> handle(HttpRequest request, UnauthorizedException exception) {
        return HttpResponse.unauthorized()
                .header("WWW-Authenticate", "Basic realm=\"User Visible Realm\"");
    }
}

这个类会替换Micronaut默认的未授权异常处理器,所有未授权请求都会自动带上指定的响应头。


内容的提问来源于stack exchange,提问作者Michel Nagme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:06:03