Windows-classic-samples 之 BasicPlugins:用自定义授权与 PowerShell 会话配置构建 Management OData Web Service

原创2026-10-14 12:37:03824 阅读
文章标签:示例工程

Windows-classic-samples 之 BasicPlugins:用自定义授权与 PowerShell 会话配置构建 Management OData Web Service

本指南围绕 Windows-classic-samples 仓库中的 BasicPlugins 示例展开,介绍如何通过实现 Microsoft.Management.OData.CustomAuthorization 与 System.Management.Automation.Remoting.PSSessionConfiguration 两个接口,把 PowerShell cmdlet 以 OData Web Service 的形式暴露给外部调用方。读完本文,你将掌握 Management OData(PSWS,PowerShell Web Services)插件体系的核心扩展点、配额(Quota)机制、会话初始化逻辑,以及从功能安装、编译到 IIS 端点部署的完整实战流程。

示例定位:让 PowerShell cmdlet 变成 OData 服务

BasicPlugins 是一个面向 Windows Server 2012 R2 的 C# 类库示例(项目文件位于 Samples/BasicPlugins/cs/BasicPlugins.sln),它演示的是 Windows PowerShell 基础 OData Web Service 的插件实现。Management OData Web Service 本身由系统提供,但要让服务对外暴露 PowerShell cmdlet,必须由第三方实现两个关键接口:

  • Microsoft.Management.OData.CustomAuthorization:负责对所有传入用户进行授权,并为每个用户分配资源配额;
  • System.Management.Automation.Remoting.PSSessionConfiguration:负责为已授权用户提供 PowerShell 会话配置(即初始会话状态)。

BasicPlugins 提供的是一套"最小可用"的参考实现:它授权所有用户(pass-through),并为所有用户返回相同的会话配置与配额。从源码结构看,示例刻意保持简单,目的是让开发者把注意力集中在接口契约与部署链路上,而非复杂的业务鉴权逻辑。

环境与前置条件

根据 BasicPlugins 的 README:

  • 操作系统:仅支持服务器端,客户端不受支持;目标系统为 Windows Server 2012 R2。README 同时说明,示例最初基于 Windows 8.1 / Windows Server 2012 R2 与 Visual Studio 2013 编写,多数情况下可用后续版本原样编译运行。
  • 开发工具:需要 Microsoft Visual Studio 2010、2013 或更高版本(任意 SKU),但不能在 Visual Studio Express 2013 for Windows 中编译。
  • 服务器功能:构建前必须在目标机器上安装 Management OData IIS Extension 功能。

由于示例只提供插件类库与部署脚本,真正可运行的服务端点还需要 IIS 与 WCF 支撑,因此安装脚本会一次性启用多项 Windows 功能(详见下文"功能安装"小节)。

核心接口一:CustomAuthorization——透明授权与配额控制

源码 CustomAuthorization.cs 实现了授权接口,其行为概括为"放行一切用户,配额人人相等"。

AuthorizeUser:返回当前 Windows 身份并给出配额

public override WindowsIdentity AuthorizeUser(SenderInfo senderInfo, out UserQuota userQuota)
{
    var maxConcurrentRequests = ConfigurationManager.AppSettings["MaxConcurrentRequests"];
    var maxRequestsPerTimeslot = ConfigurationManager.AppSettings["MaxRequestsPerTimeslot"];
    var timeslotSize = ConfigurationManager.AppSettings["TimeslotSize"];

    userQuota = new UserQuota(
        maxConcurrentRequests != null ? int.Parse(maxConcurrentRequests, CultureInfo.CurrentUICulture) : DefaultMaxConcurrentRequests,
        maxRequestsPerTimeslot != null ? int.Parse(maxRequestsPerTimeslot, CultureInfo.CurrentUICulture) : DefaultMaxRequestsPerTimeslot,
        timeslotSize != null ? int.Parse(timeslotSize, CultureInfo.CurrentUICulture) : DefaultTimeslotSize);

    return WindowsIdentity.GetCurrent();
}

AuthorizeUser 是接口的核心入口:服务每次收到请求都会调用它完成身份判定,并通过 out UserQuota 返回该用户可用的资源配额。本实现直接返回进程当前 Windows 身份(WindowsIdentity.GetCurrent()),即"来者不拒"的透明授权;配额则优先读取应用配置(appSettings),未配置时回落到代码中的默认常量:

配置键 默认常量 默认值 含义
MaxConcurrentRequests DefaultMaxConcurrentRequests 10 单个用户的最大并发请求数
MaxRequestsPerTimeslot DefaultMaxRequestsPerTimeslot 4 单个时间片内允许的最大请求数
TimeslotSize DefaultTimeslotSize 1 时间片大小(秒)

GetMembershipId:固定成员组

public override string GetMembershipId(SenderInfo senderInfo)
{
    return DefaultManagementSystemStateId;
}

GetMembershipId 返回一个固定 GUID(E7D438A1-C0BA-49D6-952E-EF7C45CB737D),意味着所有用户都被视为同一组成员。该机制可用于将不同用户划分到不同的管理状态组,而本示例刻意让所有用户共享同一组。

核心接口二:PSSessionConfiguration——构建初始会话状态

源码 SessionConfiguration.cs 实现 PSSessionConfiguration,负责为每个用户准备 PowerShell 会话环境。

GetApplicationPrivateData:返回 null

public override PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
{
    return null;
}

该方法用于向会话传递应用私有数据,本示例直接返回 null,表示不注入任何附加数据。

GetInitialSessionState:自动装载模块与脚本函数

public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
{
    var initialSessionState = InitialSessionState.CreateDefault();

    var dir = HttpContext.Current != null ? HttpContext.Current.Server.MapPath(".") : Directory.GetCurrentDirectory();

    initialSessionState.ImportPSModule(Directory.EnumerateFiles(dir, "*.psm1")
        .Select(s => Path.Combine(dir, Path.GetFileNameWithoutExtension(s))).ToArray());

    foreach (var cmdletFileName in Directory.EnumerateFiles(dir, "*-*.ps1"))
    {
        initialSessionState.Commands.Add(
            new SessionStateFunctionEntry(Path.GetFileNameWithoutExtension(cmdletFileName), File.ReadAllText(Path.Combine(dir, cmdletFileName))));
    }

    return initialSessionState;
}

这段实现体现了两条约定:

  1. 模块自动装载:扫描 Web 应用物理目录下所有 *.psm1 模块文件,通过 InitialSessionState.ImportPSModule 全部导入会话;
  2. 脚本转函数:扫描目录下所有命名形如 *-*.ps1 的 PowerShell 脚本,把文件名(不含扩展名)作为函数名、文件内容作为函数体,注册为 SessionStateFunctionEntry。

目录的确定逻辑是:如果处于 HTTP 上下文(HttpContext.Current != null),使用 Server.MapPath(".") 定位 Web 站点物理路径;否则回退到当前工作目录。这意味着你只需把自定义模块或脚本放进端点物理目录,部署后即可自动出现在每个用户的 PowerShell 会话中——这正是"Basic Plugins"名字的由来:无需修改插件代码,通过放文件即可扩展可用命令。

服务装配:Web.config 与 WCF 宿主

Web.config 中的插件装配

Web.config 是服务端的核心配置文件,关键片段如下:

<managementOdata schemaFileName="Schema.mof" resourceMappingFileName="Schema.xml">
   <customAuthorization type="Microsoft.Samples.Management.OData.BasicPlugins.CustomAuthorization" assembly=".\Microsoft.Samples.Management.OData.BasicPlugins.dll" />
   <powershell>
      <sessionConfiguration type="Microsoft.Samples.Management.OData.BasicPlugins.SessionConfiguration" assembly=".\Microsoft.Samples.Management.OData.BasicPlugins.dll" />
   </powershell>
   <commandInvocation enabled="true" />
   <wcfDataServicesConfig>
   </wcfDataServicesConfig>
</managementOdata>

要点说明:

  • <managementOdata> 节类型为 Microsoft.Management.Odata.Core.DSConfiguration, Microsoft.Management.OData, Version=3.0.0.0,通过 schemaFileName 与 resourceMappingFileName 分别指向 MOF 数据模型文件与资源映射文件;
  • customAuthorization 与 sessionConfiguration 两个子节点分别把上述两个 C# 类注册为服务插件,assembly 指向编译产物 DLL;
  • commandInvocation enabled="true" 开启命令调用能力;
  • <system.serviceModel> 中通过 serviceAuthorizationManagerType 挂接系统自带的 CustomAuthorizationManager,并开启 aspNetCompatibilityEnabled="true"(ASP.NET 兼容模式);
  • <system.webServer> 中显式配置认证方式:关闭匿名认证,开启基本认证(basicAuthentication),Windows 认证关闭。注意部署脚本随后会用 appcmd 再次强制应用这组认证策略。

WCF 服务宿主文件

Microsoft.Management.Odata.svc 是整个服务的入口:

<%@ ServiceHost Language="C#" Debug="true"
    Factory="System.Data.Services.DataServiceHostFactory, System.Data.Services, Version=3.5.0.0, ..."
    Service="Microsoft.Management.Odata.DataService, Microsoft.Management.OData, Version=3.0.0.0, ..." %>

它通过 DataServiceHostFactory 承载 Microsoft.Management.Odata.DataService,从而以 WCF Data Service 的方式对外提供 OData 协议访问。

数据模型:Schema.mof 与 Schema.xml

Management OData 服务用一对文件描述"对外暴露哪些资源、这些资源映射到哪些 cmdlet":

  • Schema.mof:定义 CIM 类模型。示例声明了 PswsTest_Service 与 PswsTest_Process 两个实体类,以及 PswsTest_DependentService、PswsTest_ProcessModule、PswsTest_ProcessStartInfo、PswsTest_FileVersionInfo、PswsTest_Encoding 等 [ComplexType] 复杂类型。类字段带有 CIM 限定符,例如 [Key] 标记主键、[Required] 标记必填、[EmbeddedInstance("...")] 声明内嵌实例类型、[Etag] 标记乐观并发字段。
  • Schema.xml:定义资源到 cmdlet 的映射。文件指定 SchemaNamespace 为 PswsTest、容器名为 PSWSEntityContainer,并为两个资源建立映射:
    • Service → PswsTest_Service:查询映射 Get-Service、更新映射 Set-Service、创建映射 New-Service,并通过 FieldParameterMap 把 MOF 字段(如 ServiceName)绑定到 cmdlet 参数(如 Name);
    • Process → PswsTest_Process:查询映射 Get-Process,支持 Name、Id 参数集。

每个 <CmdletImplementation> 内部还细分 <Query>、<Update>、<Create> 等操作块并列出允许透传的公共参数(如 ErrorVariable、WarningVariable、OutVariable、OutBuffer),这决定了外部通过 OData 调用时可以使用哪些 cmdlet 参数。

编译与构建

示例编译产物为程序集 Microsoft.Samples.Management.OData.BasicPlugins,项目配置(BasicPlugins.csproj)中值得注意的点:

  • 目标框架为 .NET Framework 4.0(TargetFrameworkVersion v4.0),输出类型为类库(Library),Debug / Release 输出目录分别为 bin\Debug\ 与 bin\Release\;
  • 引用 Microsoft.Management.OData(版本 3.0.0.0)与 System.Management.Automation(版本 3.0.0.0),另含 System.Configuration、System.Web 等标准程序集;
  • 编译单元只有三个文件:CustomAuthorization.cs、SessionConfiguration.cs、AssemblyInfo.cs。

方式一:Visual Studio 构建

  1. 启动 Visual Studio,选择 File > Open > Project/Solution;
  2. 进入 Samples/BasicPlugins/cs 目录,双击打开 BasicPlugins.sln;
  3. 按 F7(Visual Studio 2013 中为 F6),或通过 Build > Build Solution 构建。

方式二:命令行构建

  1. 打开命令提示符,进入示例目录 Samples/BasicPlugins/cs;
  2. 执行:
msbuild BasicPlugins.sln

两种方式产物相同:bin\Debug\ 或 bin\Release\ 下的 Microsoft.Samples.Management.OData.BasicPlugins.dll,后续部署脚本会优先从这几个位置定位该 DLL。

服务器功能安装:InstallModata.ps1

构建(或运行)前需先安装 Management OData 相关 Windows 功能。README 给出的步骤是:

  1. 打开提升权限(管理员)的 PowerShell 窗口;
  2. 执行 Set-ExecutionPolicy -ExecutionPolicy Unrestricted 放开脚本执行策略;
  3. 运行 InstallModata.ps1(README 中写法为 PswsBasicPlugins\C#\setup\InstallModata.ps1,仓库内实际路径为 Samples/BasicPlugins/cs/setup/InstallModata.ps1)。

该脚本全部通过 Dism.exe 在线启用功能,依次包含:

命令 启用的功能 作用
第一条 ManagementOdata Management OData Service 核心功能
第二条 WCF-HTTP-Activation45 .NET 4.5 WCF HTTP 激活
第三条 IIS-BasicAuthentication、IIS-WindowsAuthentication IIS 基本/Windows 认证
第四条 IIS-WebServerManagementTools、IIS-ManagementConsole、IIS-ManagementScriptingTools、IIS-ManagementService、IIS-IIS6ManagementCompatibility、IIS-Metabase、IIS-WMICompatibility、IIS-LegacyScripts、IIS-LegacySnapIn IIS 管理工具与旧版兼容组件

所有命令均带 /all /Quiet /NoRestart 参数,即静默启用相关依赖且不自动重启,适合自动化部署。

端点部署:SetupEndpoint.ps1 与 SetupIISConfig.ps1

一键部署入口

SetupEndpoint.ps1 是 README 中"运行示例"步骤实际调用的脚本,它依次完成三件事:

  1. 定位插件程序集:依次尝试当前目录 .\Microsoft.Samples.Management.OData.BasicPlugins.dll、..\bin\Debug\ 与 ..\bin\Release\,全部找不到则抛出错误提示先编译或先拷贝 DLL(对应 setup/Readme.txt 中的说明);
  2. 安装功能:调用 .\installModata.ps1;
  3. 配置 IIS 端点:调用 SetupIISConfig.ps1,并传入以下参数:
-site MODataSvc
-path $env:HOMEDRIVE\inetpub\wwwroot\Modata
-cfgfile .\Web.config
-port 7000
-app MODataSvc
-svc .\Microsoft.Management.Odata.svc
-schema .\Schema.mof
-dispatchXml .\Schema.xml
-customPluginAssembly <定位到的 DLL 路径>

脚本结束时打印端点的根 URI:

http://localhost:7000/MODataSvc/Microsoft.Management.Odata.svc

IIS 配置脚本的完整行为

SetupIISConfig.ps1 是真正的 IIS 编排者,其执行流程可归纳为:

  1. 参数校验与 IIS 体检:校验 Web.config、.svc、Schema.mof、Schema.xml、插件 DLL 五个文件均存在;随后通过注册表 W3SVC 键、Microsoft.Web.Administration.ServerManager 对象与 w3svc 服务状态三重检查确认 IIS 已安装且运行;
  2. 清理旧环境:删除名为 MOData 的应用程序池,删除同名站点,并用 appcmd add backup 以 MODataIISSetup_<时间戳> 为名备份当前 IIS 配置;
  3. 落盘文件:创建物理目录(默认 %systemdrive%\inetpub\wwwroot\Modata),把 Web.config(重命名为 web.config)、.svc、Schema.mof、Schema.xml、插件 DLL 拷贝进去;
  4. 创建应用池与站点:appcmd add apppool /name:MOData 并设置托管运行时版本为 v4.0(/managedRuntimeVersion:"v4.0");appcmd add site 创建绑定到 http://*:7000 的站点,再添加 /MODataSvc 应用并指向物理目录;
  5. 认证配置:appcmd unlock config 解锁 access、anonymousAuthentication、basicAuthentication、windowsAuthentication 四个配置节,然后强制设置——匿名认证关闭、基本认证开启、Windows 认证开启(与 Web.config 的默认值一致);
  6. 防火墙放行:用 netsh advfirewall 关闭入站通知,并为指定端口添加名为 MOData_IIS_Port 的 TCP 入站允许规则;
  7. 收尾:启动全部站点,等待 10 秒后完成部署。

整个脚本把"删旧站→备份配置→建新站→开认证→放端口"串成一条幂等性较好的部署流水线,重复执行也不会残留旧配置。

运行示例的完整操作序列

综合 README 与脚本,在 Windows Server 2012 R2 上跑通该示例的完整顺序如下:

第一步:准备环境

# 提升权限的 PowerShell 窗口
Set-ExecutionPolicy -ExecutionPolicy Unrestricted

第二步:构建插件

用 Visual Studio 打开 BasicPlugins.sln 并构建,或命令行执行 msbuild BasicPlugins.sln。

第三步:部署端点

cd Samples/BasicPlugins/cs
.\setupEndPoint.ps1

脚本会自动安装 Management OData 功能、配置 IIS 并生成防火墙规则。

第四步:访问验证

在浏览器或 OData 客户端中访问:

http://localhost:7000/MODataSvc/Microsoft.Management.Odata.svc

即可看到以 OData 协议暴露的 Service 与 Process 资源;对 Process 执行查询会经由映射调用 Get-Process,对 Service 的增改则对应 New-Service / Set-Service,从而实现"HTTP 请求驱动 PowerShell cmdlet"的远程管理能力。

小结

BasicPlugins 示例用最精简的代码完整演示了 Management OData 插件开发的两个决定性接口:CustomAuthorization 决定"谁能用、能用多少",PSSessionConfiguration 决定"会话里有什么命令"。在此基础上,仓库内的 Schema.mof 与 Schema.xml 展示了如何用 CIM 模型把 PowerShell cmdlet 抽象为 OData 资源,而 InstallModata.ps1、SetupEndpoint.ps1 与 SetupIISConfig.ps1 则给出了从功能安装到 IIS 站点、认证、防火墙的端到端部署范式。对于需要基于 PowerShell 构建可编程管理面(REST/OData 风格)的开发者,这是一份值得逐行研读的官方参考起点。

登录后查看全文
Windows-classic-samples