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

Micronaut OpenID认证对接外部IdP 刷新令牌自动流转配置问题

Micronaut网关透传IdP JWT及自动刷新实现方案

基础配置调整

首先修改原有安全配置,开启刷新令牌获取权限,保留IdP返回的原生令牌数据:

security:
  authentication: idtoken 
  oauth2:
    clients:
      provider: 
        client-secret: '${OAUTH_CLIENT_SECRET:yyy}' 
        client-id: '${OAUTH_CLIENT_ID:xxx}'
        supported-grant-types: 
          - authorization_code
          - refresh_token
        scopes:
          - openid
          - offline_access # 必须加该scope才能获取IdP下发的刷新令牌
        openid:
          issuer: '${OIDC_ISSUER_DOMAIN}/oauth2'
  token:
    jwt:
      # 禁用Micronaut自行生成令牌,直接使用IdP返回的ID Token
      generator:
        enabled: false
  endpoints:
    logout:
      get-allowed: true 

实现IdP原生刷新令牌返回

默认的认证成功处理器只会返回ID Token到Cookie,你需要自定义OauthAuthenticationSuccessHandler Bean替换默认实现,取出IdP返回的原生刷新令牌写入Cookie:

import io.micronaut.context.annotation.Replaces;
import io.micronaut.security.oauth2.endpoint.authorization.response.DefaultOauthAuthenticationSuccessHandler;
import io.micronaut.security.oauth2.endpoint.authorization.response.OauthAuthenticationSuccessHandler;
import io.micronaut.security.oauth2.endpoint.token.response.OAuth2AuthenticationResponse;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.cookie.Cookie;
import jakarta.inject.Singleton;

@Singleton
@Replaces(DefaultOauthAuthenticationSuccessHandler.class)
public class CustomAuthSuccessHandler implements OauthAuthenticationSuccessHandler {
    @Override
    public HttpResponse onSuccess(HttpRequest request, Authentication authentication) {
        HttpResponse response = super.onSuccess(request, authentication);
        // 从认证信息中取出IdP返回的原生刷新令牌
        OAuth2AuthenticationResponse oauthResp = (OAuth2AuthenticationResponse) authentication.getAttributes().get("oauth2Response");
        String refreshToken = oauthResp.getRefreshToken();
        // 写入刷新令牌Cookie,生产环境需开启Secure、SameSite属性
        Cookie refreshCookie = Cookie.of("REFRESH_TOKEN", refreshToken)
                .httpOnly(true)
                .path("/")
                .maxAge(2592000); // 有效期和IdP侧刷新令牌有效期保持一致
        response.cookie(refreshCookie);
        return response;
    }
}

自动令牌刷新流程实现

Micronaut没有内置全套自动刷新逻辑,无需引入第三方库,通过自定义全局过滤器即可实现:

  • 定义优先级高于安全认证过滤器的全局过滤器,拦截所有需要认证的请求
  • 从请求Cookie中取出ID Token和刷新令牌,校验ID Token是否过期
  • 若ID Token过期,调用OauthClient的refreshToken方法向IdP请求新的令牌
  • 将新的ID Token、新的刷新令牌(若IdP返回)更新到响应Cookie中
  • 将新的ID Token写入请求头Authorization: Bearer ${新令牌},继续向后传递,实现透传给下游服务
  • 若刷新令牌本身过期,直接返回401状态码,触发用户重新认证

安全注意事项

  • 刷新令牌为高敏感凭证,对应的Cookie必须设置HttpOnly=true,生产环境必须开启Secure=true、SameSite=Lax/Strict
  • 刷新令牌的Cookie有效期需和IdP侧配置的刷新令牌有效期完全一致
  • 透传令牌到下游时,直接使用IdP签发的ID Token即可,无需做额外签名校验,下游服务自行校验JWT有效性即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:06:05