Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert Identity Server 4 persisted ApiSecret values using T-SQL

I have been through the Identity Server 4 QuickStart for using Entity Framework for persistent storage of configuration and operational data. In the QuickStart, the ApiResources are loaded into the database in code. The Api secret is set with

        new ApiResource("api1", "My API")
        {
            ApiSecrets = { new Secret("secret".Sha256())}
        }

in the ApiResource constructor. When, in Startup.InitializeDatabase, that ApiResource is added to the ConfigurationDbContext.ApiResources DbSet,

        foreach(var resource in Config.GetApiResources())
        {
            context.ApiResources.Add(resource.ToEntity());
        }
        context.SaveChanges();

the record in the child ApiSecrets table contains a readable text value in the ApiSecrets.Value field.

    K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=

I would like to manage my configuration data through SQL scripts, but I can't figure out how to set the ApiSecrets.Value correctly. I've tried using T-SQL HASHBYTES('SHA2_256', 'secret'), but that produces an unreadable (I think binary) value in ApiSecrets.Value. Is there a way to set the hashed secret correctly through T-SQL?

like image 467
Zoe Avatar asked Jan 15 '19 21:01

Zoe


3 Answers

You were on the right track to use HASHBYTES, just need to get the Base64 hash out of the BinaryHash:

DECLARE @HASHBYTES VARBINARY(128) = hashbytes('sha2_256', 'secret')
SELECT cast(N'' as xml).value('xs:base64Binary(sql:variable("@HASHBYTES"))', 'varchar(128)');
like image 144
Vidmantas Blazevicius Avatar answered Oct 29 '22 01:10

Vidmantas Blazevicius


Hope this would help.

CREATE FUNCTION [dbo].[ConvertToSha256ForIdentityServer](@secret varchar(128))
RETURNS varchar(128) AS
BEGIN
    DECLARE @HASHBYTES VARBINARY(128) = hashbytes('sha2_256', @secret)
    RETURN (SELECT top 1 cast(N'' as xml).value('xs:base64Binary(sql:variable("@HASHBYTES"))', 'varchar(128)'));
END

to insert

MERGE INTO dbo.[ClientSecrets] AS TARGET
USING (
        VALUES
         (dbo.ConvertToSha256ForIdentityServer('mysecret'),'SharedSecret',getdate(),1)
      )
      AS Source ([Value],[Type],[Created],[ClientId])
ON Target.[ClientId] = source.[ClientId]
WHEN matched THEN
  UPDATE SET
      [Value] = Source.[Value],
      [Type] = Source.[Type]

WHEN NOT matched BY target THEN
  INSERT ([Value],[Type],[Created],[ClientId])
  VALUES ([Value],[Type],[Created],[ClientId]);
like image 37
Iyddaz Avatar answered Oct 29 '22 00:10

Iyddaz


You can use the algorithm below to create secret, then you can store it in SQL:

using System.Security.Cryptography;

static class Extentions
{

    public static string Sha256(this string input)
    {
        using (SHA256 shA256 = SHA256.Create())
        {
            byte[] bytes = Encoding.UTF8.GetBytes(input);
            return Convert.ToBase64String(((HashAlgorithm)shA256).ComputeHash(bytes));
        }
    }
}


void Main()
{
    Console.WriteLine( "secret-as-guid".Sha256());
}

you can also use passwordgenerator.net

like image 25
Derviş Kayımbaşıoğlu Avatar answered Oct 29 '22 01:10

Derviş Kayımbaşıoğlu