Search code examples
c#cookieswebformsasp.net-core-mvchttpcontext

Extracting the claims from existing AspNetCore.Cookie in a webform, coming from the MVC


Scenario - The objective

The flow starts with a login. When the user is authenticated, it's redirected to a MVC app to create the session and store it in an http cookie, using this standard Sign-In implementation with cookie scheme.

When the claims are created (and shown in the browser), the user goes to the webform site without needing to pass the credentials over again, since it is previously authenticated and then such claims should be printed in the browser as the MVC does.

Consider that the MVC & Webform are hosted in different servers, hence here comes under the hood the reverse proxy, to redirect the claims in the http header.

Architectural design

Arquitectural Design

The MVC implementation

The below code is in the MVC project, which creates the cookie shown in the screenshot:

public async Task CreateIdentityAsync()
{
   var claims = httpContext.User.Claims;
   var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefauls.AuthenticationScheme);
   var principal = new ClaimsPrincipal(userIdentity);

   await httpContext.SignInAsync(CookieAuthenticationDefauls.AuthenticationScheme, principal);
}

The claims information is showing something like:

and the cookie is stored in the browser like: Cookie created in MVC

The Webform implementation

When user clicks on "Web form" in the MVC site, it calls the reverse proxy and then redirects the http header.

The auth cookie is shown as follows:

web form cookie

The code:

public partial class SiteMaster : MasterPage
{
    private const string NO_COOKIES_MESSAGE = "No Cookies available";
    private const string ASPNET_COOKIES = ".AspNetCore.Cookies";

    protected void Page_Load(object sender, EventArgs e)
    {
        var cookie = Request.Cookies.Get(ASPNET_COOKIES);
        var value = cookie?.Value ?? NO_COOKIES_MESSAGE;

        lblCookie.ForeColor = value == NO_COOKIES_MESSAGE ? Color.Red : Color.Black;
        lblCookie.Text = value;  // <-- SHOW THE COOKIE ON THE WEBFORM

        var claims = GetTheClaimsFromCookies(value);  // <-- HOW TO GET THE CLAIMS???
    }

    private IEnumerable<Claims> GetTheClaimsFromCookies(string value) 
    {
        // LOGIC GOES HERE...
    }
}

Questions / approaches

There come the following doubts in my mind, based on AuthenticateAsync():

  • Should I decode the cookie?
  • How can I inject back the cookie in the Authentication identity?

Solution

  • Thanks to the link posted by @davidfowl, in addition to the YARP IHttpForwarder implementation found in the Todo repo, I unfold that the TicketDataFormat for .NET Core and OWIN - TiketDataFormat do the trick, as shown here

    EDIT: I forgot to mention that in all applications, the CookieAuthenticationOption attribute must be options.Cookie.SameSite = SameSiteMode.Lax