你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure Functions 的 Dapr 机密输入绑定

通过 Dapr 机密输入绑定,可以在函数执行期间将机密数据读取为输入。

若要了解 Dapr 扩展的设置和配置详细信息,请参阅 Dapr 扩展概述

Example

可以使用以下 C# 模式之一创建 C# 函数:

Execution model Description
独立工作模型 函数代码在单独的 .NET 工作进程中运行。 与受支持的 .NET 和 .NET Framework 版本结合使用。 若要了解详细信息,请参阅 独立辅助角色模型中运行 C# Azure Functions 的指南
In-process model 函数代码与 Functions 宿主进程在同一进程中运行。 仅支持 .NET 的长期支持 (LTS) 版本。 若要了解详细信息,请参阅 使用 Azure Functions 开发 C# 类库函数
[FunctionName("RetrieveSecret")]
public static void Run(
    [DaprServiceInvocationTrigger] object args,
    [DaprSecret("kubernetes", "my-secret", Metadata = "metadata.namespace=default")] IDictionary<string, string> secret,
    ILogger log)
{
    log.LogInformation("C# function processed a RetrieveSecret request from the Dapr Runtime.");
}

以下示例使用 "RetrieveSecret" 绑定和 DaprSecretInput 创建一个 DaprServiceInvocationTrigger 函数:

@FunctionName("RetrieveSecret")
public void run(
    @DaprServiceInvocationTrigger(
        methodName = "RetrieveSecret") Object args,
    @DaprSecretInput(
        secretStoreName = "kubernetes", 
        key = "my-secret", 
        metadata = "metadata.namespace=default") 
        Map<String, String> secret,
    final ExecutionContext context)

在以下示例中,Dapr 机密输入绑定与 app 对象注册的 Dapr 调用触发器配对:

const { app, trigger } = require('@azure/functions');

app.generic('RetrieveSecret', {
    trigger: trigger.generic({
        type: 'daprServiceInvocationTrigger',
        name: "payload"
    }),
    extraInputs: [daprSecretInput],
    handler: async (request, context) => {
        context.log("Node function processed a RetrieveSecret request from the Dapr Runtime.");
        const daprSecretInputValue = context.extraInputs.get(daprSecretInput);

        // print the fetched secret value
        for (var key in daprSecretInputValue) {
            context.log(`Stored secret: Key=${key}, Value=${daprSecretInputValue[key]}`);
        }
    }
});

The following examples show Dapr triggers in a function.json file and PowerShell code that uses those bindings.

Here's the function.json file for daprServiceInvocationTrigger:

{
  "bindings": 
    {
      "type": "daprSecret",
      "direction": "in",
      "name": "secret",
      "key": "my-secret",
      "secretStoreName": "localsecretstore",
      "metadata": "metadata.namespace=default"
    }
}

For more information about function.json file properties, see the Configuration section.

In code:

using namespace System
using namespace Microsoft.Azure.WebJobs
using namespace Microsoft.Extensions.Logging
using namespace Microsoft.Azure.WebJobs.Extensions.Dapr
using namespace Newtonsoft.Json.Linq

param (
    $payload, $secret
)

# PowerShell function processed a CreateNewOrder request from the Dapr Runtime.
Write-Host "PowerShell function processed a RetrieveSecretLocal request from the Dapr Runtime."

# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $secret | ConvertTo-Json

Write-Host "$jsonString"

以下示例显示了一个 Dapr 机密输入绑定,该绑定使用 v2 Python 编程模型。 若要在 Python 函数应用代码中使用 daprSecret 绑定和 daprServiceInvocationTrigger,请执行以下操作:

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="RetrieveSecret")
@app.dapr_service_invocation_trigger(arg_name="payload", method_name="RetrieveSecret")
@app.dapr_secret_input(arg_name="secret", secret_store_name="localsecretstore", key="my-secret", metadata="metadata.namespace=default")
def main(payload, secret: str) :
    # Function should be invoked with this command: dapr invoke --app-id functionapp --method RetrieveSecret  --data '{}'
    logging.info('Python function processed a RetrieveSecret request from the Dapr Runtime.')
    secret_dict = json.loads(secret)

    for key in secret_dict:
        logging.info("Stored secret: Key = " + key +
                     ', Value = ' + secret_dict[key])

Attributes

In the in-process model, use the DaprSecret to define a Dapr secret input binding, which supports these parameters:

Parameter Description
SecretStoreName 要获取机密的机密存储的名称。
Key 标识要获取的机密名称的密钥。
Metadata Optional. 元数据属性的数组,格式为 "key1=value1&key2=value2"

Annotations

通过 DaprSecretInput 注释,可以让函数访问机密。

Element Description
secretStoreName Dapr 机密存储的名称。
key 密钥值。
metadata Optional. 元数据值。

Configuration

下表说明了在代码中设置的绑定配置属性。

Property Description
key 密钥值。
secretStoreName Name of the secret store as defined in the local-secret-store.yaml component file.
metadata 元数据命名空间。

下表解释了在 function.json 文件中设置的绑定配置属性。

function.json property Description
key 密钥值。
secretStoreName Name of the secret store as defined in the local-secret-store.yaml component file.
metadata 元数据命名空间。

下表介绍了在 Python 代码中设置的 @dapp.dapr_secret_input 的绑定配置属性。

Property Description
secret_store_name 机密存储的名称。
key 密钥值。
metadata 元数据命名空间。

See the Example section for complete examples.

Usage

要使用 Dapr 机密输入绑定,请先设置 Dapr 机密存储组件。 可在 Dapr 官方文档中详细了解可使用的组件及其设置方式。

To use the daprSecret in Python v2, set up your project with the correct dependencies.

  1. 创建并激活虚拟环境

  2. requirements.text 文件中添加以下行:

    azure-functions==1.18.0b3
    
  3. 在终端中安装 Python 库。

    pip install -r .\requirements.txt
    
  4. 修改具有以下配置的 local.setting.json 文件:

    "PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
    

Next steps

详细了解 Dapr 机密。