Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Identity - Setting CookieDomain at runtime

How can I set the CookieDOmain in the CookieAuthenticationOptions at runtime if i want to pull this value from the Request.Url or from some settings stored in my database?

I want to support sub-domains, but also support multi-tenants too which each have different domains.

At the moment this is configured I don't have access to either of these.

Paul

like image 200
Paul Hinett Avatar asked Apr 10 '14 13:04

Paul Hinett


People also ask

What is AspNet identity?

ASP.NET Identity is Microsoft's user management library for ASP.NET. It includes functionality such as password hashing, password validation, user storage, and claims management. It usually also comes with some basic authentication, bringing its own cookies and multi-factor authentication to the party.

What is Microsoft AspNet identity Owin?

Microsoft.AspNet.Identity.OWIN. This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. This is used when you add sign in functionality to your application and call into OWIN Cookie Authentication middleware to generate a cookie.


1 Answers

You can assign your own cookie provider:

CookieAuthProvider myProvider = new CookieAuthProvider();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
   AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
   LoginPath = new PathString("/Account/Login"),
   Provider = myProvider
});

Either implement your own, or simply inherit from the existing provider:

public class CookieAuthProvider : CookieAuthenticationProvider
{
    public override void ResponseSignIn(CookieResponseSignInContext context)
    {
      //Alter you cookie options
      //context.CookieOptions.Domain  =  "www...";      
      base.ResponseSignIn(context);
    }
 }

And implement ResponseSignIn, it is called when an endpoint has provided sign in information before it is converted into a cookie. By implementing this method the claims and extra information that go into the ticket may be altered.

You'll be passed a CookieResponseSignInContext, which exposes CookieOptions property that can be replaced or altered during the ResponseSignIn call.

Code references from Katana project:

  • ICookieAuthenticationProvider

  • CookieResponseSignInContext

  • CookieAuthenticationHandler

like image 157
MK. Avatar answered Sep 18 '22 21:09

MK.