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

Feign Basic Auth凭证更新后无法生效,如何实现运行时刷新?

运行时刷新Feign Basic Auth凭证的解决方案

问题原因

你的BasicAuthRequestInterceptor是在Spring Bean初始化阶段一次性获取凭证并固定下来的,后续即使凭证更新,由于Bean是单例且不会重新初始化,所以无法获取新的凭证值。

解决方案

方案一:自定义动态RequestInterceptor

放弃使用BasicAuthRequestInterceptor,自定义拦截器实现每次请求时动态获取最新凭证:

package com.example.test.config;

import com.example.test.service.CustomCredentialsProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.springframework.http.HttpHeaders;

@Configuration
public class FeignClientConfiguration {

    @Autowired
    private CustomCredentialsProvider customCredentialsProvider;

    @Bean
    public RequestInterceptor dynamicBasicAuthInterceptor() {
        return requestTemplate -> {
            // 每次请求时实时获取最新凭证
            Credentials credentials = customCredentialsProvider.getCredentials();
            String authPair = credentials.getUser() + ":" + credentials.getPassword();
            String encodedAuth = Base64.getEncoder().encodeToString(authPair.getBytes(StandardCharsets.UTF_8));
            requestTemplate.header(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);
        };
    }
}

方案二:确保凭证提供者感知配置变化

如果你的CustomCredentialsProvider是从配置中心/配置文件读取凭证,给它添加@RefreshScope注解,让Spring在配置更新时自动刷新该Bean:

package com.example.test.service;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@RefreshScope
public class CustomCredentialsProvider {

    @Value("${auth.service.username}")
    private String user;

    @Value("${auth.service.password}")
    private String password;

    public Credentials getCredentials() {
        return new Credentials(user, password);
    }
}

验证方式

修改凭证后发起Feign调用,通过日志或抓包工具查看请求头中的Authorization字段,确认其编码内容对应最新的用户名和密码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:27:24