【问题标题】:Decrypt ".AspNetCore.Session" cookie in ASP.NET Core解密 ASP.NET Core 中的“.AspNetCore.Session”cookie
【发布时间】:2016-11-18 19:08:32
【问题描述】:

在 Asp.Net 核心中,当您将应用配置为 app.UseSession() 时会创建一个 cookie。 默认情况下,cookie 名为“.AspNetCore.Session”。它的值标识要使用的会话。目前,我将会话数据保存在 sql server 上。我需要知道“.AspNetCore.Session”的解密值,以便我可以在数据库中查找会话。

有没有办法解密这个值?我知道 ASP.NET 必须以某种方式在幕后进行。

【问题讨论】:

  • 我想知道它是否与 Forms Security 具有相同的加密/解密功能。也许 FormsAuthentication.Decrypt() 使用的任何东西都可能有效或至少值得一试。
  • 这是一个IDataProtector,后跟base64编码。要解密,您首先需要将 base64 解码为字节数组,然后应用其中的一部分:stackoverflow.com/a/37543433/1132334。 “秘密”就是这部分:CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", ...)
  • 感谢@dlatikay 的指导。从您提供的链接中,我在 C:\mypath 中放了什么?

标签: c# asp.net asp.net-core asp.net-core-mvc asp.net-core-1.0


【解决方案1】:

session source 拥有一切,但您应该知道它,ISessionStoreIDistributedSessionStore 为您提供了一个会话密钥供您使用。

与其对 cookie 格式做出假设,是什么阻止您使用商店 API?

【讨论】:

  • ISessionStore 只定义了一个公共成员,即 Create 方法。那么如何使用它来获取SessionKey,它是存储会话数据的sql server 表的键?
【解决方案2】:

我不得不从Microsoft.AspNetCore.Session 中提取私有Pad 函数,但我能够得到我需要的东西:

public class DiscussionController : Controller
{   
    private readonly IDataProtector _dataProtector;        

    public DiscussionController(IDataProtectionProvider dataProtectionProvider)
    {
        var protectorPurpose = "whatever purpose you want";

        _dataProtector = dataProtectionProvider.CreateProtector(protectorPurpose);
    }

    public IActionResult Index()
    {     
       HttpContext.Request.Cookies.TryGetValue(".AspNetCore.Session", out string cookieValue);

       var protectedData = Convert.FromBase64String(Pad(cookieValue));

       var unprotectedData = _dataProtector.Unprotect(protectedData);

       var humanReadableData = System.Text.Encoding.UTF8.GetString(unprotectedData);

        return Ok();
    }

    private string Pad(string text)
    {
        var padding = 3 - ((text.Length + 3) % 4);
        if (padding == 0)
        {
            return text;
        }
        return text + new string('=', padding);
    }    
}

Pad 函数取自:https://github.com/aspnet/AspNetCore/blob/87629bbad906e9507026692904b6bcb5021cdd33/src/Middleware/Session/src/CookieProtection.cs#L61-L69

【讨论】:

  • 感谢您的建设性意见@LeoGurdian。链接和代码已更新。
猜你喜欢
  • 1970-01-01
  • 2020-03-01
  • 2017-08-08
  • 1970-01-01
  • 2015-08-09
  • 2016-10-23
  • 2016-06-01
  • 2021-06-01
  • 2016-07-10
相关资源
最近更新 更多