Search code examples
asp.net-mvc-3owin.security

Change the domain in a cookie (ASP.Net and Microsoft.Owin.Security)


I use the libraries Microsoft.Owin.Security, Microsoft.Owin.Security.OpenIDConnect and Microsoft.Owin.Security.Cookies. It works fine and I can create a security cookie. But in the security cookie is the domain AAA.de. How I can change the domain in the cookie to .AAA.de ?

This is the code I use to sign in the user.

public void SignIn()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties(
                new Dictionary<string, string>
                {
                    {Startup.PolicyKey, Startup.SignInPolicyId}
                })
                {
                    RedirectUri = Redirect,
                }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

Thanks for your help.


Solution

  • The cookie domain can be configured by using a custom Cookie provider - this is typically configured as part of the Application Startup process - you've probably also got an App_Start folder with a Startup.Auth.cs class in it (if you've started with the typical base project.

    Your provider would look something like:

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

    You can then call this from your startup class via:

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

    Based heavily on this answer to "Asp.Net Identity - Setting CookieDomain at runtime"