ASP.NET_SessionId + OWIN Cookies do not send to browser
Asked Answered
O

9

171

I have a strange problem with using Owin cookie authentication.

When I start my IIS server authentication works perfectly fine on IE/Firefox and Chrome.

I started doing some testing with Authentication and logging in on different platforms and I have come up with a strange error. Sporadically the Owin framework / IIS just doesn't send any cookies to the browsers. I will type in a username and password which is correct the code runs but no cookie gets delivered to the browser at all. If I restart the server it starts working then at some point I will try login and again cookies stop getting delivered. Stepping over the code does nothing and throws no errors.

 app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            CookieHttpOnly = true,
            AuthenticationType = "ABC",
            LoginPath = new PathString("/Account/Login"),
            CookiePath = "/",
            CookieName = "ABC",
            Provider = new CookieAuthenticationProvider
               {
                  OnApplyRedirect = ctx =>
                  {
                     if (!IsAjaxRequest(ctx.Request))
                     {
                        ctx.Response.Redirect(ctx.RedirectUri);
                     }
                 }
               }
        });

And within my login procedure I have the following code:

IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                            authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

var authentication = HttpContext.Current.GetOwinContext().Authentication;
var identity = new ClaimsIdentity("ABC");
identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.User_ID.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Role, role.myRole.ToString()));
    authentication.AuthenticationResponseGrant =
        new AuthenticationResponseGrant(identity, new AuthenticationProperties()
                                                   {
                                                       IsPersistent = isPersistent
                                                   });

authenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = isPersistent}, identity);

Update 1: It seems that one cause of the problem is when I add items to session the problems start. Adding something simple like Session.Content["ABC"]= 123 seems to create the problem.

What I can make out is as follows: 1) (Chrome)When I login I get ASP.NET_SessionId + my authentication cookie. 2) I go to a page that sets a session.contents... 3) Open a new browser (Firefox) and try login and it does not receive an ASP.NET_SessionId nor does it get a Authentication Cookie 4) Whilst the first browser has the ASP.NET_SessionId it continues to work. The minute I remove this cookie it has the same problem as all the other browsers I am working on ip address (10.x.x.x) and localhost.

Update 2: Force creation of ASPNET_SessionId first on my login_load page before authentication with OWIN.

1) before I authenticate with OWIN I make a random Session.Content value on my login page to start the ASP.NET_SessionId 2) then I authenticate and make further sessions 3) Other browsers seem to now work

This is bizarre. I can only conclude that this has something to do with ASP and OWIN thinking they are in different domains or something like that.

Update 3 - Strange behaviour between the two.

Additional strange behaviour identified - Timeout of Owin and ASP session is different. What I am seeing is that my Owin sessions are staying alive longer than my ASP sessions through some mechanism. So when logging in: 1.) I have a cookied based auth session 2.) I set a few session variables

My session variables(2) "die" before the owin cookie session variable forces re-login, which causes unexpected behaviour throughout my entire application. (Person is logged in but is not really logged in)

Update 3B

After some digging I saw some comments on a page that say the "forms" authentication timeout and session timeout need to match. I am thinking normally the two are in sync but for whatever reason the two are not in sync.

Summary of Workarounds

1) Always create a Session first before authentication. Basically create session when you start the application Session["Workaround"] = 0;

2) [Experimental] if you persist cookies make sure your OWIN timeout / length is longer than your sessionTimeout in your web.config (in testing)

Oleary answered 23/12, 2013 at 5:39 Comment(2)
Can confirm that adding a session call to ActionResult Login and ActionResult ExternalLogin fixed this issue. I'm sure only one is needed but I have both in place.Tresa
Thank you!...Adding Session in ExternalLogin fixed it for me...this is voodoo magic...i have already wasted 6 hrs to hunt this issue down..Germinative
B
170

I have encountered the same problem and traced the cause to OWIN ASP.NET hosting implementation. I would say it's a bug.

Some background

My findings are based on these assembly versions:

  • Microsoft.Owin, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  • Microsoft.Owin.Host.SystemWeb, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  • System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

OWIN uses it's own abstraction to work with response Cookies (Microsoft.Owin.ResponseCookieCollection). This implementation directly wraps response headers collection and accordingly updates Set-Cookie header. OWIN ASP.NET host (Microsoft.Owin.Host.SystemWeb) just wraps System.Web.HttpResponse and it's headers collection. So when new cookie is created through OWIN, response Set-Cookie header is changed directly.

But ASP.NET also uses it's own abstraction to work with response Cookies. This is exposed to us as System.Web.HttpResponse.Cookies property and implemented by sealed class System.Web.HttpCookieCollection. This implementation does not wrap response Set-Cookie header directly but uses some optimizations and handful of internal notifications to manifest it's changed state to response object.

Then there is a point late in request lifetime where HttpCookieCollection changed state is tested (System.Web.HttpResponse.GenerateResponseHeadersForCookies()) and cookies are serialized to Set-Cookie header. If this collection is in some specific state, whole Set-Cookie header is first cleared and recreated from cookies stored in collection.

ASP.NET session implementation uses System.Web.HttpResponse.Cookies property to store it's ASP.NET_SessionId cookie. Also there is some basic optimization in ASP.NET session state module (System.Web.SessionState.SessionStateModule) implemented through static property named s_sessionEverSet which is quite self explanatory. If you ever store something to session state in your application, this module will do a little more work for each request.


Back to our login problem

With all these pieces your scenarios can be explained.

Case 1 - Session was never set

System.Web.SessionState.SessionStateModule, s_sessionEverSet property is false. No session id's are generated by session state module and System.Web.HttpResponse.Cookies collection state is not detected as changed. In this case OWIN cookies are sent correctly to the browser and login works.

Case 2 - Session was used somewhere in application, but not before user tries to authenticate

System.Web.SessionState.SessionStateModule, s_sessionEverSet property is true. Session Id's are generated by SessionStateModule, ASP.NET_SessionId is added to System.Web.HttpResponse.Cookies collection but it's removed later in request lifetime as user's session is in fact empty. In this case System.Web.HttpResponse.Cookies collection state is detected as changed and Set-Cookie header is first cleared before cookies are serialized to header value.

In this case OWIN response cookies are "lost" and user is not authenticated and is redirected back to login page.

Case 3 - Session is used before user tries to authenticate

System.Web.SessionState.SessionStateModule, s_sessionEverSet property is true. Session Id's are generated by SessionStateModule, ASP.NET_SessionId is added to System.Web.HttpResponse.Cookies. Due to internal optimization in System.Web.HttpCookieCollection and System.Web.HttpResponse.GenerateResponseHeadersForCookies() Set-Cookie header is NOT first cleared but only updated.

In this case both OWIN authentication cookies and ASP.NET_SessionId cookie are sent in response and login works.


More general problem with cookies

As you can see the problem is more general and not limited to ASP.NET session. If you are hosting OWIN through Microsoft.Owin.Host.SystemWeb and you/something is directly using System.Web.HttpResponse.Cookies collection you are at risk.

For example this works and both cookies are correctly sent to browser...

public ActionResult Index()
{
    HttpContext.GetOwinContext()
        .Response.Cookies.Append("OwinCookie", "SomeValue");
    HttpContext.Response.Cookies["ASPCookie"].Value = "SomeValue";

    return View();
}

But this does not and OwinCookie is "lost"...

public ActionResult Index()
{
    HttpContext.GetOwinContext()
        .Response.Cookies.Append("OwinCookie", "SomeValue");
    HttpContext.Response.Cookies["ASPCookie"].Value = "SomeValue";
    HttpContext.Response.Cookies.Remove("ASPCookie");

    return View();
}

Both tested from VS2013, IISExpress and default MVC project template.

Blaine answered 20/1, 2014 at 12:49 Comment(12)
I have spent a few days trying to debug and resolve this issue in our test environment. The only workaround i found is the same as you suggested (setting session before user authenticates). I have reported the issue to katanaproject... katanaproject.codeplex.com/workitem/197, so maybe someone will comment there.Blaine
This is a pretty serious flaw, especially since they packaged owin the template for vs2013.Oleary
I have also hit this problem (see https://mcmap.net/q/144975/-asp-net-identity-2-0-not-creating-a-valid-authentication-when-signing-in/236860). I will try workaround, but I feel that this problem needs fixing at source. What I find strange is that there isn't generally more 'noise' about this - I appreciate that not everyone is using Sessions, but even so I would have expected more urgency to get this fixed.Dinky
I have just read and added to the thread at katanaproject.codeplex.com/workitem/197 Unbelievably, they are saying that this won't be fixed until the release of vNext - surely that simply isn't good enough?Dinky
For anyone that wants to investigate this further, I have created a test project at github.com/Neilski/IdentityBugDemoDinky
Running into this problem because of the use of Controller.TempData which uses Session as the backing store. Can readily reproduce the inability to login if an ASP_NET.SessionId cookie doesn't exist from a previous request.Percuss
I'm running into this problem in my current project without even touching the Session, nor temp data. Though, when creating a blank mvc project, everything works as expected. I even tried the app.UseKentorOwinCookieSaver(); to no avail. Debugging the app pipeline shows me that the cookie added to the response header is .AspNet.Correlation.Google, no trace of .AspNet.ExternalCookie. Have been debugging this all day... ;(Wolfie
Finally! What a strange issue this is. Thank you. This is still an issue over two years after this answer was written.Dicarlo
Oh great! After a month thread i've found the solution. In ASPNET MVC5 and OWIN 3.0.1 is still an issue... :(Vd
I'm using asp.net 4.6 web form and identity 2.0 and it still doesn't work!! #43099245 is there any sure work around? but where I have to create a new session?Megasporangium
it is mid 2019 and this issue still exists! (.net 4.5.2, Owin 4.0.1)Maryammaryann
I try this but it didn't work, #64299184 any help?Farlee
F
60

In short, the .NET cookie manager will win over the OWIN cookie manager and overwrite cookies set on the OWIN layer. The fix is to use the SystemWebCookieManager class, provided as a solution on the Katana Project here. You need to use this class or one similar to it, which will force OWIN to use the .NET cookie manager so there are no inconsistencies:

public class SystemWebCookieManager : ICookieManager
{
    public string GetRequestCookie(IOwinContext context, string key)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
        var cookie = webContext.Request.Cookies[key];
        return cookie == null ? null : cookie.Value;
    }

    public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (options == null)
        {
            throw new ArgumentNullException("options");
        }

        var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

        bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
        bool pathHasValue = !string.IsNullOrEmpty(options.Path);
        bool expiresHasValue = options.Expires.HasValue;

        var cookie = new HttpCookie(key, value);
        if (domainHasValue)
        {
            cookie.Domain = options.Domain;
        }
        if (pathHasValue)
        {
            cookie.Path = options.Path;
        }
        if (expiresHasValue)
        {
            cookie.Expires = options.Expires.Value;
        }
        if (options.Secure)
        {
            cookie.Secure = true;
        }
        if (options.HttpOnly)
        {
            cookie.HttpOnly = true;
        }

        webContext.Response.AppendCookie(cookie);
    }

    public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (options == null)
        {
            throw new ArgumentNullException("options");
        }

        AppendResponseCookie(
            context,
            key,
            string.Empty,
            new CookieOptions
            {
                Path = options.Path,
                Domain = options.Domain,
                Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            });
    }
}

In your application startup, just assign it when you create your OWIN dependencies:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    ...
    CookieManager = new SystemWebCookieManager()
    ...
});

A similar answer has been provided here but it does not include all of the code-base required to solve the problem, so I see a need to add it here because the external link to the Katana Project may go down and this should be fully chronicled as a solution here as well.

Flitter answered 23/2, 2016 at 13:16 Comment(13)
thanks, its work me, but also i clear all session by calling this ControllerContext.HttpContext.Session.RemoveAll(); in externallogincallback functionOrmiston
Is applies to ASP.NET Webforms 4.6.1 ? My webApp uses ASP.NET Webforms, OWIN, ADFSBurgoo
@Burgoo Does your web app use OWIN cookies? Then yes.Flitter
In code Startup.ConfigureAuth we have app.UseCookieAuthentication and app.UseWsFederationAuthentication and finally app.UseStageMarkerBurgoo
@Flitter You might consider an edit, my team hit this bug and it was rare and random, it hid from us through DEV and UAT environments. This quote from your answer did not hold for us: ".NET cookie manager will always win." That would be easy to find and fix, if the OWIN cookies were always overwritten none of our OIDC middleware would have made it off our dev workstations. But the randomness meant the bug made it all the way to production for 2 days before it hit us at scale (half our internal uses could not login via AAD). Mind if I remove the word "always" from your answer?Appling
@Appling But can you explain why?Flitter
@Appling I changed my answer but I guess the real question is under what circumstances does the .NET cookie manager not win over OWIN's?Flitter
@Flitter The only answer I have is "at scale". We only used AAD for a month before we discovered one of our largest clients had one of the 3 top-level domains used by AAD sign-in blocked in their firewall, and had to gut the entire implementation for another authentication provider.Appling
Ive tried all in this thread. It works for me only when Fiddler is open. Seems fiddler is doing something that the code isn't. Any ideas?Method
@Method It sounds like what you’re experiencing is an untrusted SSL certificate between you and the server. Fiddler adds a middleware whereby it creates its own CA cert and signs new certs for each connection, so your machine may effectively trust the server with Fiddler running but not trust it otherwise.Flitter
@Flitter I think I'm having the same issue, and I try your solution it didn't work, I'm using .net 4.6 with OWIN is this still applicable? does anyone have any ideaFarlee
@Farlee I'm not sure but github.com/aspnet/AspNetKatana/wiki/… says: This issue has already been addressed in the next version of Katana (ASP.NET Core) where the storage of response cookies has been standardized to always store them in the response header collection.Flitter
use SystemWebCookieManager and SystemWebChunkingCookieManager from Microsoft.Owin.Host.SystemWeb instead of your own copy of codeKilmarnock
S
49

Starting with the great analysis by @TomasDolezal, I had a look at both the Owin and the System.Web source.

The problem is that System.Web has its own master source of cookie information and that isn't the Set-Cookie header. Owin only knows about the Set-Cookie header. A workaround is to make sure that any cookies set by Owin are also set in the HttpContext.Current.Response.Cookies collection.

I've made a small middleware (source, nuget) that does exactly that, which is intended to be placed immediately above the cookie middleware registration.

app.UseKentorOwinCookieSaver();

app.UseCookieAuthentication(new CookieAuthenticationOptions());
Smock answered 17/11, 2014 at 17:17 Comment(6)
Will give this a try. Since after asp.net Identity 2.2.0-alpha1 I began having problems not only at login but also at logging the user out (the user won't log out on logout click |generally, in case when I left the website open for sometime without doing anything|).. And after setting a session just before the user logs in solved the login problem but the logout problem persists.. Thanks for your effort.. By the way, is there anything I should do except for the installation of the package?Recipe
You have to activate it with app.UseKentorCookieMiddlewareSaver(); in Startup.Auth.cs. It should handle logout cookie clearing too.Smock
Thank you so much Anders Abel, both login and logout works fine now. But the code in above comment needs to be altered (because I followed it :) without any success) to be: app.UseKentorOwinCookieSaver() and maybe included in you original answer as in the package's GitHub page.Recipe
Thanks for noticing the incorrect doc. It's actually already fixed on the GitHub page, but I've updated in my answer here as well now.Smock
@AndersAbel I am trying to add Meetup signups for this github project: github.com/owin-middleware/OwinOAuthProviders''. I added Asana just the other day and had no issues, but for some reason, with Meetup, the await AuthenticationManager.GetExternalLoginInfoAsync() method in Account//ExternalLoginCallback is returning null. UNfortunately, your NuGet package did not solve my issue. I was wondering if you had some time to review with me as you may be able to better troubleshoot the issue and push to your project.Recommendatory
Hello, later I noticed that logout is not working again and for anyone having the same issue I solved that explicitly logging out the application cookie: authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie)Recipe
E
22

Katana team answered to the issue Tomas Dolezar raised, and posted documentation about workarounds:

Workarounds fall into two categories. One is to re-configure System.Web so it avoids using the Response.Cookies collection and overwriting the OWIN cookies. The other approach is to re-configure the affected OWIN components so they write cookies directly to System.Web's Response.Cookies collection.

  • Ensure session is established prior to authentication: The conflict between System.Web and Katana cookies is per request, so it may be possible for the application to establish the session on some request prior to the authentication flow. This should be easy to do when the user first arrives, but it may be harder to guarantee later when the session or auth cookies expire and/or need to be refreshed.
  • Disable the SessionStateModule - If the application is not relying on session information, but the session module is still setting a cookie that causes the above conflict, then you may consider disabling the session state module.
  • Reconfigure the CookieAuthenticationMiddleware to write directly to System.Web's cookie collection.
app.UseCookieAuthentication(new CookieAuthenticationOptions
                                {
                                    // ...
                                    CookieManager = new SystemWebCookieManager()
                                });

See SystemWebCookieManager implementation from the documentation (link above)

More information here

Edit

Below the steps we took to solve the issue. Both 1. and 2. solved the problem also separately but we decided to apply both just in case:

1. Use SystemWebCookieManager

2. Set the session variable:

protected override void Initialize(RequestContext requestContext)
{
    base.Initialize(requestContext);

    // See https://mcmap.net/q/143053/-asp-net_sessionid-owin-cookies-do-not-send-to-browser/
    requestContext.HttpContext.Session["FixEternalRedirectLoop"] = 1;
}

(side note: the Initialize method above is the logical place for the fix because base.Initialize makes Session available. However, the fix could also be applied later because in OpenId there's first an anonymous request, then redirect to the OpenId provider and then back to the app. The problems would occur after the redirect back to the app while the fix sets the session variable already during the first anonymous request thus fixing the problem before any redirect back even happens)

Edit 2

Copy-paste from the Katana project 2016-05-14:

Add this:

app.UseCookieAuthentication(new CookieAuthenticationOptions
                                {
                                    // ...
                                    CookieManager = new SystemWebCookieManager()
                                });

...and this:

public class SystemWebCookieManager : ICookieManager
{
    public string GetRequestCookie(IOwinContext context, string key)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
        var cookie = webContext.Request.Cookies[key];
        return cookie == null ? null : cookie.Value;
    }

    public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (options == null)
        {
            throw new ArgumentNullException("options");
        }

        var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

        bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
        bool pathHasValue = !string.IsNullOrEmpty(options.Path);
        bool expiresHasValue = options.Expires.HasValue;

        var cookie = new HttpCookie(key, value);
        if (domainHasValue)
        {
            cookie.Domain = options.Domain;
        }
        if (pathHasValue)
        {
            cookie.Path = options.Path;
        }
        if (expiresHasValue)
        {
            cookie.Expires = options.Expires.Value;
        }
        if (options.Secure)
        {
            cookie.Secure = true;
        }
        if (options.HttpOnly)
        {
            cookie.HttpOnly = true;
        }

        webContext.Response.AppendCookie(cookie);
    }

    public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (options == null)
        {
            throw new ArgumentNullException("options");
        }

        AppendResponseCookie(
            context,
            key,
            string.Empty,
            new CookieOptions
            {
                Path = options.Path,
                Domain = options.Domain,
                Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            });
    }
}
Enjoin answered 14/12, 2015 at 12:31 Comment(7)
I find this answer much more straightforward and easier to fix the issue. Thanks, - Maybe I spoke too suddenly. This didn't solve my issue.Disbelieve
@Disbelieve Included the steps we took to solve the issue. Did you find out whether your issue was related?Enjoin
I'm using Web Api 2 + Owin middleware + redis cache for session management for authentication. I tried to use SystemWebCookieManager and it didn't solve the issue I was having where the auth cookies weren't being set. Using "UseKentorOwinCookieSaver" solved it but I'm not too fond of an extra external dependency...Disbelieve
Clearing the session worked for me. No external dependency needed. Put this ControllerContext.HttpContext.Session.RemoveAll(); in your ExternalLogin() action, before calling ChallengeResult(). I don't know whether it's the best solution, but it's the simplest.Azral
This is a better solution @Alisson ControllerContext.HttpContext.Session?.RemoveAll();Alpenhorn
@Alpenhorn sure, just take note the ?. (null-conditional operator) only works in C# 6.Azral
The Katana documentation for this issue is now here: github.com/aspnet/AspNetKatana/wiki/…Autochthon
R
9

Answers have been provided already, but in owin 3.1.0, there is a SystemWebChunkingCookieManager class that can be used.

https://github.com/aspnet/AspNetKatana/blob/dev/src/Microsoft.Owin.Host.SystemWeb/SystemWebChunkingCookieManager.cs

https://raw.githubusercontent.com/aspnet/AspNetKatana/c33569969e79afd9fb4ec2d6bdff877e376821b2/src/Microsoft.Owin.Host.SystemWeb/SystemWebChunkingCookieManager.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    ...
    CookieManager = new SystemWebChunkingCookieManager()
    ...
});
Rainmaker answered 22/7, 2017 at 0:39 Comment(6)
Is this still a problem in 3.1.0?Philodendron
Yes, it is still an issue in 3.1.0 for me and needed this cookie manager, as the default one is still the ChunkingCookieManager.Rainmaker
can be used where? and how?Portraitist
@Rainmaker thanks. I think yesterday I missed the distinction between SystemCCM and CCM so I’ll definitely check this outPortraitist
even after adding above line its not working for me. i am using 3.1.0 version. Mainly i am able to login first time but after logout its does not allow me to login.Mogerly
I still had to clear my cookies before invoking HttpContext.GetOwinContext().Authentication.Challenge() (so that I would avoid an extra redirect back to the IdP), but starting to look good now.Shipboard
L
3

If you are setting cookies in OWIN middleware yourself, then using OnSendingHeaders seems to get round the problem.

For example, using the code below owinResponseCookie2 will be set, even though owinResponseCookie1 is not:

private void SetCookies()
{
    var owinContext = HttpContext.GetOwinContext();
    var owinResponse = owinContext.Response;

    owinResponse.Cookies.Append("owinResponseCookie1", "value1");

    owinResponse.OnSendingHeaders(state =>
    {
        owinResponse.Cookies.Append("owinResponseCookie2", "value2");
    },
    null);

    var httpResponse = HttpContext.Response;
    httpResponse.Cookies.Remove("httpResponseCookie1");
}
Livvi answered 22/3, 2016 at 11:59 Comment(0)
V
3

I faced the Similar Issue with Visual Studio 2017 and .net MVC 5.2.4, Updating Nuget Microsoft.Owin.Security.Google to lastest version which currently is 4.0.1 worked for me! Hope this Helps someone!

Vermicide answered 8/11, 2019 at 7:51 Comment(1)
Saved my bacon on this one! Was having an issue with Android Chrome specifically losing authentication at random. Nothing else in this thread worked. I'm using VS2019 and ASP MVC 5.Naiad
T
2

I had the same symptom of the Set-Cookie header not being sent but none of these answers helped me. Everything worked on my local machine but when deployed to production the set-cookie headers would never get set.

It turns out it was a combination of using a custom CookieAuthenticationMiddleware with WebApi along with WebApi compression support

Luckily I was using ELMAH in my project which let me to this exception being logged:

System.Web.HttpException Server cannot append header after HTTP headers have been sent.

Which led me to this GitHub Issue

Basically, if you have an odd setup like mine you will want to disable compression for your WebApi controllers/methods that set cookies, or try the OwinServerCompressionHandler.

Taber answered 6/5, 2016 at 17:43 Comment(0)
T
2

The fastest one-line code solution:

HttpContext.Current.Session["RunSession"] = "1";

Just add this line before CreateIdentity method:

HttpContext.Current.Session["RunSession"] = "1";
var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
_authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberLogin }, userIdentity);
Twibill answered 11/6, 2016 at 8:34 Comment(3)
Where you put this code HttpContext.Current.Session["RunSession"] = "1"; ? in Globa.asax Session_Start ?Burgoo
It is in fact simplest and fastest solution available, and until solution of that problem will not be included in the Framework (already announced that it will) - I, for example, would prefer one-liner, instead of a class + bunch of dependencies. This solution is underestimated IMHO.Propagandize
I added it in my AuthManager at the top of IssueAuthToken methodTwibill

© 2022 - 2024 — McMap. All rights reserved.