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

如何使用Spring AI 1.1.2调用需认证的远程MCP服务?

Spring AI 1.1.2 远程MCP服务身份认证配置方案

针对远程MCP服务需要在请求头添加Authorization的场景,提供两种配置方案:

一、静态固定认证头(适用于token长期有效)

直接在配置文件中添加请求头参数,Spring AI的streamable-http连接支持原生配置请求头:

streamable-http:
  connections:
    weather-streamable:
      url: http://127.0.0.1:8004/
      endpoint: streamable
      headers:
        # Bearer认证格式,替换为实际token
        Authorization: "Bearer your-static-access-token"
        # 若为Basic认证,格式为 "Basic 用户名密码Base64编码值"
        # Authorization: "Basic dXNlcjE6cGFzc3dvcmQ="

配置完成后,Spring AI的MCP客户端会自动在请求远程服务时携带该Authorization头。

二、动态认证头(适用于token需动态生成/刷新)

如果token需要从认证服务动态获取或定期刷新,可通过自定义请求拦截器实现:

1. 编写认证拦截器

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;

public class McpAuthInterceptor implements ClientHttpRequestInterceptor {

    // 可注入token获取服务(如OAuth2客户端),此处示例简化处理
    private final TokenService tokenService;

    public McpAuthInterceptor(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 动态获取最新token
        String accessToken = tokenService.getLatestToken();
        request.getHeaders().add("Authorization", "Bearer " + accessToken);
        return execution.execute(request, body);
    }

    // 模拟token获取服务
    public static class TokenService {
        public String getLatestToken() {
            // 实际实现中调用认证接口获取token
            return "dynamic-refreshed-token";
        }
    }
}

2. 配置带拦截器的MCP连接

修改原配置类,注册自定义的StreamableHttpConnection并绑定拦截器:

import org.springframework.ai.mcp.streamable.http.StreamableHttpConnection;
import org.springframework.ai.mcp.streamable.http.StreamableHttpConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class McpClientConfig {

    @Bean
    public StreamableHttpConnection weatherStreamableHttpConnection() {
        // 创建带拦截器的RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add(new McpAuthInterceptor(new McpAuthInterceptor.TokenService()));

        // 绑定到指定MCP连接
        return StreamableHttpConnectionFactory.builder()
                .name("weather-streamable")
                .url("http://127.0.0.1:8004/")
                .endpoint("streamable")
                .restTemplate(restTemplate)
                .build();
    }

    @Bean
    public ChatClient chatClient(ChatModel chatModel, ToolCallbackProvider tools) {
        return ChatClient.builder(chatModel)
                .defaultToolCallbacks(tools.getToolCallbacks())
                .build();
    }
}

注意:自定义StreamableHttpConnection Bean会覆盖配置文件中同名连接的配置,无需重复在yaml中定义该连接。

验证方式

调用ChatClient触发MCP工具回调时,可通过日志或抓包工具检查请求头是否包含正确的Authorization字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 10:36:04