【问题标题】:In Identity Server 4, how do I read the encrypted refresh token(string) saved in database in order to get the access token?在 Identity Server 4 中,如何读取保存在数据库中的加密刷新令牌(字符串)以获取访问令牌?
【发布时间】:2020-01-08 15:46:01
【问题描述】:

我有一个 Identity Server 4 池(2 个服务器),一个服务器正在发出访问令牌(JWT)和一个刷新令牌,刷新令牌保存在数据库表中。(PersistedGrants 表)。现在,当访问令牌过期时,我想从第二个服务器读取刷新令牌并调用 RequestRefreshTokenAsync 以取回一组新令牌。如何在应用程序中读取数据库刷新令牌?

【问题讨论】:

    标签: identityserver4 refresh-token


    【解决方案1】:

    我不确定这是否是您要问的,但客户端中的refresh_token 使用以下代码转换为 IdentityServer4 的 PersistedGrants 表上的数据库 Id,我相信我已从IdentityServer4前段时间的源码:

    using System;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace HandleToKey
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                if (args.Length < 1)
                {
                    Console.WriteLine("No argument provided, you may want to provide with a token handle.");
                    Console.WriteLine("Usage: HandleToKey.exe [tokenHandle]");
                }
                else
                {
                    var input = args.First();
                    using (var sha = SHA256.Create())
                    {
                        input = $"{input}:refresh_token";
                        var bytes = Encoding.UTF8.GetBytes(input);
                        var hash = sha.ComputeHash(bytes);
                        var result = Convert.ToBase64String(hash);
    
                        Console.WriteLine(result);
                        Console.WriteLine("Press any key to continue...");
                        Console.ReadKey();
                    }
                }
            }
        }
    }
    

    相关字节是 using 中的代码,我认为(我不记得)是用于在实际源代码中创建和咨询持久授权的代码,或类似的代码。它将输入与":refresh_token" 连接起来,使用UTF8 Charmap 获取byte[],并计算其SHA256 哈希,然后将其编码为Base64,结果应该是Id。

    您也可以通过将字符串更改为 ":access_token" 而不是 refresh_token 来使用 access_token 引用获得相同的结果。

    无论如何,我只将它用于调试目的。 我希望您避免在生产站点上使用此代码,因为如果您让我们了解更多信息,我相信会有更好的方法来解决您的实际问题。

    【讨论】:

    • 我用于身份服务器 4 的代码与此处的代码类似 github.com/IdentityServer/IdentityServer4/tree/master/samples/… 这将数据保存到 [PersistedGrants] 表中,该表具有以下列 [Key],[Type ],[SubjectId],[ClientId],[CreationTime],[Expiration],[Data] Key 列是保存刷新令牌的列。现在,我想使用这个令牌来获取一组新的令牌。(在生产场景中,我不能依赖内存中的令牌。)
    • 发出的refresh_token和数据库上的key不一样。这正是我的代码所做的,将 refresh_token 转换为数据库密钥。 AFAIK 无法以相反的方式进行操作,即:获取密钥并获取实际的 refresh_token 或 tokenHandle
    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2022-10-13
    • 2021-01-29
    • 2018-11-26
    • 2017-03-22
    相关资源
    最近更新 更多