How get cookieValue in first request/response in ASP.NET Core

Viewed 31

I'm doing a project with .NET 6 and I must get the cookie value in first Response from server to client to put it in AntiforgeryAdditionalData. I implemented IAntiforgeryAdditionalDataProvider as following:

public class QueueTokensAntiforgeryAdditionalDataProvider : IAntiforgeryAdditionalDataProvider
{
    private const string TokenKey = "QueueTokensKey";

    public string GetAdditionalData(HttpContext context)
    {
        Dictionary<string, string> existingTokens = new();

        var cookieValue = ((Microsoft.AspNetCore.Session.SessionMiddleware.SessionEstablisher)((Microsoft.AspNetCore.Session.DistributedSession)context.Session)._tryEstablishSession.Target)._cookieValue;

        existingTokens.Add("cookieValue", cookieValue);

        SetTokens(context, existingTokens);

        return cookieValue;
    }

    public bool ValidateAdditionalData(HttpContext context, string additionalData)
    {
        try
        {
            var tokens = GetTokens(context);

            if (tokens["cookieValue"] == additionalData)
            {
                return true;
            }

            return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    private static void SetTokens(HttpContext context, Dictionary<string, string> existingTokens)
    {
        context.Session.SetString(TokenKey, FNAJsonSerializer.Serialize(existingTokens));
    }

    private static Dictionary<string, string> GetTokens(HttpContext context)
    {
        Dictionary<string, string> dic = new();

        dic.Add("cookieValue", context.Session.GetString(TokenKey));

        return dic;
    }
}

In above code there is a line as following:

var cookieValue = ((Microsoft.AspNetCore.Session.SessionMiddleware.SessionEstablisher)((Microsoft.AspNetCore.Session.DistributedSession)context.Session)._tryEstablishSession.Target)._cookieValue;

that I picked it up in quick watch as following picture:

enter image description here

but I run into a problem in casting. I think I must use reflection to get cookieValue btu I do not know. How can I do this. Any help will be appriciated.

0 Answers
Related