当前位置: 首页 > news >正文

MCP-安全(代码实例)

安全最佳实践

安全性对于 MCP 实施至关重要,尤其是在企业环境中。务必确保工具和数据免受未经授权的访问、数据泄露和其他安全威胁。

介绍

在本课中,我们将探讨 MCP 实施的安全最佳实践。我们将涵盖身份验证和授权、数据保护、安全工具执行以及数据隐私法规合规性。

学习目标

学完本课后,您将能够:

  • 为 MCP 服务器实施安全的身份验证和授权机制。
  • 使用加密和安全存储保护敏感数据。
  • 通过适当的访问控制确保工具的安全执行。
  • 应用数据保护和隐私合规的最佳实践。

身份验证和授权

身份验证和授权对于确保 MCP 服务器的安全至关重要。身份验证回答的是“您是谁?”,而授权回答的是“您能做什么?”。

让我们看一下如何使用 .NET 和 Java 在 MCP 服务器中实现安全身份验证和授权的示例。

.NET 身份集成

ASP .NET Core Identity 提供了一个强大的框架来管理用户身份验证和授权。我们可以将其与 MCP 服务器集成,以保护对工具和资源的访问。

在将 ASP.NET Core Identity 与 MCP 服务器集成时,我们需要了解一些核心概念:

  • 身份配置:使用用户角色和声明设置 ASP.NET Core 身份。声明是关于用户的信息,例如其角色或权限,例如“管理员”或“用户”。
  • JWT 身份验证:使用 JSON Web 令牌 (JWT) 实现安全的 API 访问。JWT 是一种以 JSON 对象形式在各方之间安全传输信息的标准,由于其经过数字签名,因此可以被验证和信任。
  • 授权策略:根据用户角色定义策略,控制对特定工具的访问。MCP 使用授权策略,根据用户的角色和声明来确定哪些用户可以访问哪些工具。
public class SecureMcpStartup
{public void ConfigureServices(IServiceCollection services){// Add ASP.NET Core Identityservices.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();// Configure JWT authenticationservices.AddAuthentication(options =>{options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;}).AddJwtBearer(options =>{options.TokenValidationParameters = new TokenValidationParameters{ValidateIssuer = true,ValidateAudience = true,ValidateLifetime = true,ValidateIssuerSigningKey = true,ValidIssuer = Configuration["Jwt:Issuer"],ValidAudience = Configuration["Jwt:Audience"],IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))};});// Add authorization policiesservices.AddAuthorization(options =>{options.AddPolicy("CanUseAdminTools", policy =>policy.RequireRole("Admin"));options.AddPolicy("CanUseBasicTools", policy =>policy.RequireAuthenticatedUser());});// Configure MCP server with securityservices.AddMcpServer(options =>{options.ServerName = "Secure MCP Server";options.ServerVersion = "1.0.0";options.RequireAuthentication = true;});// Register tools with authorization requirementsservices.AddMcpTool<BasicTool>(options => options.RequirePolicy("CanUseBasicTools"));services.AddMcpTool<AdminTool>(options => options.RequirePolicy("CanUseAdminTools"));}public void Configure(IApplicationBuilder app){// Use authentication and authorizationapp.UseAuthentication();app.UseAuthorization();// Use MCP server middlewareapp.UseMcpServer();}
}

在上面的代码中,我们有:

  • 配置 ASP.NET Core Identity 用于用户管理。
  • 设置 JWT 身份验证以实现安全的 API 访问。我们指定了令牌验证参数,包括颁发者、受众和签名密钥。
  • 定义授权策略,根据用户角色控制对工具的访问。例如,“CanUseAdminTools”策略要求用户具有“Admin”角色,而“CanUseBasic”策略则要求用户进行身份验证。
  • 注册的 MCP 工具具有特定的授权要求,确保只有具有适当角色的用户才能访问它们。

Java Spring 安全集成

对于 Java,我们将使用 Spring Security 实现 MCP 服务器的安全身份验证和授权。Spring Security 提供了一个全面的安全框架,可与 Spring 应用程序无缝集成。

这里的核心概念是:

  • Spring 安全配置:设置身份验证和授权的安全配置。
  • OAuth2 资源服务器:使用 OAuth2 安全访问 MCP 工具。OAuth2 是一个授权框架,允许第三方服务交换访问令牌以实现安全的 API 访问。
  • 安全拦截器:实施安全拦截器来强制执行工具执行的访问控制。
  • 基于角色的访问控制:使用角色来控制对特定工具和资源的访问。
  • 安全注释:使用注释来保护方法和端点。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/mcp/discovery").permitAll() // Allow tool discovery.antMatchers("/mcp/tools/**").hasAnyRole("USER", "ADMIN") // Require authentication for tools.antMatchers("/mcp/admin/**").hasRole("ADMIN") // Admin-only endpoints.anyRequest().authenticated().and().oauth2ResourceServer().jwt();}@Beanpublic McpSecurityInterceptor mcpSecurityInterceptor() {return new McpSecurityInterceptor();}
}// MCP Security Interceptor for tool authorization
public class McpSecurityInterceptor implements ToolExecutionInterceptor {@Autowiredprivate JwtDecoder jwtDecoder;@Overridepublic void beforeToolExecution(ToolRequest request, Authentication authentication) {String toolName = request.getToolName();// Check if user has permissions for this toolif (toolName.startsWith("admin") && !authentication.getAuthorities().contains("ROLE_ADMIN")) {throw new AccessDeniedException("You don't have permission to use this tool");}// Additional security checks based on tool or parametersif ("sensitiveDataAccess".equals(toolName)) {validateDataAccessPermissions(request, authentication);}}private void validateDataAccessPermissions(ToolRequest request, Authentication auth) {// Implementation to check fine-grained data access permissions}
}

在上面的代码中,我们有:

  • 配置 Spring Security 来保护 MCP 端点,允许公众访问工具发现,同时要求对工具执行进行身份验证。
  • 使用 OAuth2 作为资源服务器来处理对 MCP 工具的安全访问。
  • 实施安全拦截器来强制执行工具执行的访问控制,在允许访问特定工具之前检查用户角色和权限。
  • 定义基于角色的访问控制,以根据用户角色限制对管理工具和敏感数据的访问。

数据保护和隐私

数据保护对于确保敏感信息的安全处理至关重要。这包括保护个人身份信息 (PII)、财务数据和其他敏感信息免遭未经授权的访问和泄露。

Python 数据保护示例

让我们看一个示例,了解如何使用加密和 PII 检测在 Python 中实现数据保护。

from mcp_server import McpServer
from mcp_tools import Tool, ToolRequest, ToolResponse
from cryptography.fernet import Fernet
import os
import json
from functools import wraps# PII Detector - identifies and protects sensitive information
class PiiDetector:def __init__(self):# Load patterns for different types of PIIwith open("pii_patterns.json", "r") as f:self.patterns = json.load(f)def scan_text(self, text):"""Scans text for PII and returns detected PII types"""detected_pii = []# Implementation to detect PII using regex or ML modelsreturn detected_piidef scan_parameters(self, parameters):"""Scans request parameters for PII"""detected_pii = []for key, value in parameters.items():if isinstance(value, str):pii_in_value = self.scan_text(value)if pii_in_value:detected_pii.append((key, pii_in_value))return detected_pii# Encryption Service for protecting sensitive data
class EncryptionService:def __init__(self, key_path=None):if key_path and os.path.exists(key_path):with open(key_path, "rb") as key_file:self.key = key_file.read()else:self.key = Fernet.generate_key()if key_path:with open(key_path, "wb") as key_file:key_file.write(self.key)self.cipher = Fernet(self.key)def encrypt(self, data):"""Encrypt data"""if isinstance(data, str):return self.cipher.encrypt(data.encode()).decode()else:return self.cipher.encrypt(json.dumps(data).encode()).decode()def decrypt(self, encrypted_data):"""Decrypt data"""if encrypted_data is None:return Nonedecrypted = self.cipher.decrypt(encrypted_data.encode())try:return json.loads(decrypted)except:return decrypted.decode()# Security decorator for tools
def secure_tool(requires_encryption=False, log_access=True):def decorator(cls):original_execute = cls.execute_async if hasattr(cls, 'execute_async') else cls.execute@wraps(original_execute)async def secure_execute(self, request):# Check for PII in requestpii_detector = PiiDetector()pii_found = pii_detector.scan_parameters(request.parameters)# Log access if requiredif log_access:tool_name = self.get_name()user_id = request.context.get("user_id", "anonymous")log_entry = {"timestamp": datetime.now().isoformat(),"tool": tool_name,"user": user_id,"contains_pii": bool(pii_found),"parameters": {k: "***" for k in request.parameters.keys()}  # Don't log actual values}logging.info(f"Tool access: {json.dumps(log_entry)}")# Handle detected PIIif pii_found:# Either encrypt sensitive data or reject the requestif requires_encryption:encryption_service = EncryptionService("keys/tool_key.key")for param_name, pii_types in pii_found:# Encrypt the sensitive parameterrequest.parameters[param_name] = encryption_service.encrypt(request.parameters[param_name])else:# If encryption not available but PII found, you might reject the requestraise ToolExecutionException("Request contains sensitive data that cannot be processed securely")# Execute the original methodreturn await original_execute(self, request)# Replace the execute methodif hasattr(cls, 'execute_async'):cls.execute_async = secure_executeelse:cls.execute = secure_executereturn clsreturn decorator# Example of a secure tool with the decorator
@secure_tool(requires_encryption=True, log_access=True)
class SecureCustomerDataTool(Tool):def get_name(self):return "customerData"def get_description(self):return "Accesses customer data securely"def get_schema(self):# Schema definitionreturn {}async def execute_async(self, request):# Implementation would access customer data securely# Since we used the decorator, PII is already detected and encryptedreturn ToolResponse(result={"status": "success"})

在上面的代码中,我们有:

  • 实现了一个PiiDetector类来扫描文本和参数以获取个人身份信息(PII)。
  • 创建一个EncryptionService类来使用该库处理敏感数据的加密和解密cryptography
  • 定义一个secure_tool装饰器,包装工具执行以检查 PII、记录访问并在需要时加密敏感数据。
  • secure_tool装饰器应用于示例工具(SecureCustomerDataTool),以确保它安全地处理敏感数据。
http://www.lryc.cn/news/576089.html

相关文章:

  • ubuntu安装达梦数据库
  • Java8方法引用:简洁高效的编程利器
  • algorithm ——————》双指针(移动0 复写0 快乐数 装水问题 以及数组中找几个数和为指定的元组)
  • TCP四层模型:网络协议核心解密
  • WPF 3D 开发全攻略:实现3D模型创建、旋转、平移、缩放
  • HTTP协议中Connection: Keep-Alive和Keep-Alive: timeout=60, max=100的作用
  • Linux入门攻坚——49、高可用HA之corosync/pacemaker(2)
  • Linux命令行操作基础
  • 关于css的height:100%
  • JAVA-泛型通配符的上界和下界
  • UUDS—常见NRC及其含义
  • 中国双非高校经费TOP榜数据分析
  • ROS:录制相机、IMU、GNSS等设备数据
  • gRPC技术解析与python示例
  • 楼宇自控系统以智能化管控,全方位满足建筑节约、安全与可靠运行需求
  • 像素之外的智慧:Adobe AI在动态影像与云端协作中的进阶应用
  • 如何设置 Java 的环境变量
  • 23种设计模式——单例模式的暗黑面
  • LLaMA-Factory 对 omnisql 进行 ppo dpo grpo nl2sql任务 实现难度 时间 全面对比
  • 【.net core】【sqlsugar】在where条件查询时使用原生SQL
  • spring-ai 1.0.0 学习(十八)——MCP Server
  • 修复opensuse 风滚草rabbitmq的Error: :plugins_dir_does_not_exist问题
  • 【C语言】知识总结·指针篇
  • linux dts overlay
  • Spearman检验组间相关性及SCI风格绘图
  • 基于社区电商场景的Redis缓存架构实战01-redis内核知识
  • 航拍图像中的“生命线”:基于YOLOv5的7类应急目标检测实践
  • 打造无障碍网页应用的利器:Base UI
  • Python爬虫实战:如何优雅地处理超时和延迟加载问题
  • 安全运营中的漏洞管理和相关KPI