question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't set cookie events

See original GitHub issue

Which Version of Microsoft Identity Web are you using ? Note that to get help, you need to run the latest version. 0.1.2-preview

Where is the issue?

  • Web App
    • Sign-in users
    • Sign-in users and call web APIs
  • Web API
    • Protected web APIs (Validating tokens)
    • Protected web APIs (Validating scopes)
    • Protected web APIs call downstream web APIs
  • Token cache serialization
    • In Memory caches
    • Session caches
    • Distributed caches

Other? - please describe;

Is this a new or existing app?

I’m attempting to upgrade an existing app that uses MicrosoftAccount API (i.e. AddMicrosoftAccount()). I’ve repro’d the issue in the sample 2-1-Call-MSGraph.

Repro

Add this code in ConfigureServices before AddSignIn():

            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromHours(1);
                // TODO: MAKE COOKIE EXPIRE BEFORE ACCESS TOKEN
                options.Events = new CookieAuthenticationEvents
                {
                    OnSigningIn = async (context) =>
                    {
                        var identity = context.Principal.Identity as ClaimsIdentity;

                        var userId = context.Principal.Claims.FirstOrDefault(claim => claim.Type == "preferred_username" || claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
                    }
                };
            });

            services.AddSignIn(Configuration);

Expected behavior The OnSigningIn delegate should be called when a user logs in…

Actual behavior In this case, the delegate is never called. If I use AddCookie() (as with MicrosoftAccount API), an exception “Scheme already exists: Cookies” is thrown at startup.

Additional context/ Logs / Screenshots dotnet.txt

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:12 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
toddheckelcommented, May 28, 2020

Yes, it works! Thanks, I appreciate the support!

1reaction
toddheckelcommented, May 28, 2020

Yes sorry I wasn’t clear about that. Below is the complete function. The only other changes I have made are to appsettings.json to use my AAD info.

So you are seeing the callback get called?

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                // Handling SameSite cookie according to https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1
                options.HandleSameSiteCookieCompatibility();
            });

            services.AddOptions();

            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromHours(1);
                // TODO: MAKE COOKIE EXPIRE BEFORE ACCESS TOKEN
                options.Events = new CookieAuthenticationEvents
                {
                    OnSigningIn = async (context) =>
                    {
                        var identity = context.Principal.Identity as ClaimsIdentity;

                        var userId = context.Principal.Claims.FirstOrDefault(claim => claim.Type == "preferred_username" || claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
                    }
                };
            });

            services.AddSignIn(Configuration);

            // Token acquisition service based on MSAL.NET
            // and chosen token cache implementation
            services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { Constants.ScopeUserRead })
               .AddInMemoryTokenCaches();

            /*
               // or use a distributed Token Cache by adding 
                           .AddDistributedTokenCaches();

               // and then choose your implementation. 
               // See https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#distributed-memory-cache

               // For instance the distributed in memory cache
                services.AddDistributedMemoryCache()

               // Or a Redis cache
               services.AddStackExchangeRedisCache(options =>
                    {
                        options.Configuration = "localhost";
                        options.InstanceName = "SampleInstance";
                    });

               // Or even a SQL Server token cache
               services.AddDistributedSqlServerCache(options =>
                {
                    options.ConnectionString = 
                        _config["DistCache_ConnectionString"];
                    options.SchemaName = "dbo";
                    options.TableName = "TestCache";
                });
            */
            // Add Graph
            services.AddGraphService(Configuration);

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI();

            services.AddRazorPages();
        }
Read more comments on GitHub >

github_iconTop Results From Across the Web

google chrome - Cannot set cookies in Javascript
Recently I stumbled upon a similar issue. My script couldn't store a cookie in Chromium, although it worked well on all other major...
Read more >
Set-Cookie - HTTP - MDN Web Docs
The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent...
Read more >
javascript - Why can't I set a cookie? [SOLVED]
Your function is called "setCookie" but you are calling "createCookie" in your onclick event. Change either the function name or the call so ......
Read more >
Cookies, document.cookie
A domain defines where the cookie is accessible. In practice though, there are limitations. We can't set any domain. There's no way to...
Read more >
Can't find cookie for validation in EventSubscriber
2 Answers. Some ideas: Like for the config you have to add a cache dependency for the cookie, too: $response->getCacheableMetadata()-> ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found