4

Based on what I learned from How to manually decrypt and asp.net core auth cookie I tried to do the similar. The only difference is that the cookie is set by asp.net core identity. Here is the piece in SetUp.cs:

    services.AddIdentity<ApplicationUser, IdentityRole>( options =>
        {
            options.Cookies.ApplicationCookie.AuthenticationScheme = "Cookies";
            options.Cookies.ApplicationCookie.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"));
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

And here is how I tried to setup decrypt in homeController.cs:

    var cookies = HttpContext.Request.Cookies;

    var provider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"));

    //Get a data protector to use with either approach
    var dataProtector = provider.CreateProtector("Identity.Application", "Cookies", "v2");

    //Get the decrypted cookie as plain text
    UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

    foreach (var cookie in cookies)
    {
        byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookie.Value);
        byte[] plainBytes = dataProtector.Unprotect(protectedBytes);
        string plainText = specialUtf8Encoding.GetString(plainBytes);
    }

But I always get the following error: The key {******-****} was not found in the key ring.

How to match up the key/dataProtectionProvider?

2
  • Any particular reason why you're trying to decrypt them? Also, are you sure your DataProtection keys are in sync? e.g. are both apps storing them in the same pace? Commented Jul 8, 2017 at 3:17
  • 1
    Just for fun and learning. I understand the cookie middleware decrypt them automatically. Both code blocks are in the same app and using the same folder/file. Commented Jul 9, 2017 at 3:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.