如何使用 T-SQL 插入 Identity Server 4 持久化的 ApiSecret 值

Zoe*_*Zoe 7 c# hash identityserver4

我已经通过 Identity Server 4 快速入门使用实体框架来持久存储配置和操作数据。在 QuickStart 中,ApiResources 在代码中加载到数据库中。Api 秘密设置为

        new ApiResource("api1", "My API")
        {
            ApiSecrets = { new Secret("secret".Sha256())}
        }
Run Code Online (Sandbox Code Playgroud)

在 ApiResource 构造函数中。当在 Startup.InitializeDatabase 中将该 ApiResource 添加到 ConfigurationDbContext.ApiResources DbSet 时,

        foreach(var resource in Config.GetApiResources())
        {
            context.ApiResources.Add(resource.ToEntity());
        }
        context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

子 ApiSecrets 表中的记录在 ApiSecrets.Value 字段中包含可读文本值。

    K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
Run Code Online (Sandbox Code Playgroud)

我想通过 SQL 脚本管理我的配置数据,但我不知道如何正确设置 ApiSecrets.Value。我试过使用 T-SQL HASHBYTES('SHA2_256', 'secret'),但这会在 ApiSecrets.Value 中产生一个不可读的(我认为是二进制的)值。有没有办法通过 T-SQL 正确设置散列的秘密?

Vid*_*ius 5

您的使用方向是正确的HASHBYTES,只需要从Base64以下内容中获取哈希值BinaryHash

DECLARE @HASHBYTES VARBINARY(128) = hashbytes('sha2_256', 'secret')
SELECT cast(N'' as xml).value('xs:base64Binary(sql:variable("@HASHBYTES"))', 'varchar(128)');
Run Code Online (Sandbox Code Playgroud)