asp.netasp.net-mvcasp.net-identityowinowin-middleware

Owin authentication does not emit cookie


I have following action in Login controller. For testing purposes Im not using a login form in Index action. Instead I create the claims identity and sign in. This action is GET not POST. It creates a claims identity and use that for AuthenticationManager.SignIn. But when I checked browser cookies I could not find the authentication cookie present. I am trying to figure out what has gone wrong.

    [AllowAnonymous]
    public ActionResult Index()
    {
        var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "30"));
        identity.AddClaim(new Claim(ClaimTypes.Name, "JFid"));
        identity.AddClaim(new Claim(ClaimTypes.Email, "test"));

        AuthenticationManager.SignIn(new AuthenticationProperties()
        {
            IsPersistent = true,
            ExpiresUtc = DateTime.UtcNow.AddDays(7)

        }, identity);

        return View();
    }

And also I have enabled cookie authentication in OWIN.

[assembly: OwinStartup(typeof(D.Support.WebStartup))]
namespace D.Support
{
    public class WebStartup
    {
        public void Configuration(IAppBuilder app)
        {

        app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions()
        {
            LoginPath = new PathString("/MyLoginPath"),
            CookieName = "MyCookieName",
            CookieHttpOnly = true,

        });
        }
    }
}

Solution

  • You should set the ClaimsIdentity AuthenticationType as the same as CookieOption AuthenticationType

     app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions()
        {
            LoginPath = new PathString("/MyLoginPath"),
            CookieName = "MyCookieName",
            CookieHttpOnly = true,
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
    
        });