Error unprotecting the session cookie

Is there an existing issue for this? I have searched the existing issues Describe the bug How can I avoid restarting the program? Old users always prompt this error when visiting the website? �[40m...

Please share your startup.cs — this generally happens if you’re not setting up data protection to save the keys

using InnoADLMedicalWeb.Areas.KePuBox.Controllers;
using InnoADLMedicalWeb.Areas.SportsDoctorAPI.Controllers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.IO;
using InnoADLMedicalWeb.Code.Hub;

namespace InnoADLMedicalWeb
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
            services.AddSession((options) =>
            {
                // 设置 Session 过期时间
                options.IdleTimeout = TimeSpan.FromHours(24);
            });
            services.AddHttpContextAccessor();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddCors(op =>
            {
                op.AddPolicy("AllowAll", builder =>
                {
                    builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                });
            });

            //services.AddCors(c =>

            //  c.AddPolicy("AllowAll", p =>
            //  {
            //      p.AllowAnyOrigin();
            //      p.AllowAnyMethod();
            //      p.AllowAnyHeader();
            //  })
            //  );

            // 添加Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "API",
                    Version = "v1",
                    Contact = new OpenApiContact()
                    {
                        Name = "binbin",
                        Email = "admin@bbhxwl.com"
                    }
                });
                c.SwaggerDoc("unity", new OpenApiInfo
                {
                    Title = "API",
                    Version = "v1",
                });
                try
                {
                    // 获取xml文件名
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    // 获取xml文件路径
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    // 添加控制器层注释,true表示显示控制器注释
                    c.IncludeXmlComments(xmlPath, true);
                }
                catch (Exception)
                {

                }
            });
            services.AddControllersWithViews().AddNewtonsoftJson(options =>
            {

                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;  // 设置时区为 UTC)
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            }).AddJsonOptions(config =>
            {
                config.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            services.AddRazorPages().AddRazorRuntimeCompilation();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseWebSockets();
            app.UseCors("AllowAll");
            app.UseStaticFiles();
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto
            });
            app.UseRouting();
            app.UseSession();
            app.UseAuthorization();
           
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                if (!env.IsDevelopment())
                {
                    c.InjectStylesheet("/css/swaggercustom.css");
                }
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "EnterpriseAPI");
                c.SwaggerEndpoint("/swagger/unity/swagger.json", "unity");
            });
           
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapAreaControllerRoute("areas", "AgentManage", "{area:exists}/{controller=Login}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "KePuBox", "{area:exists}/{controller=Login}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "SportsDoctorAPI", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "ResourceCenter", "{area:exists}/{controller=ResourceList}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "api", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "EnterpriseAPI", "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapHub<TongXunHub>("/TongXunHub");
                endpoints.MapHub<ForwardMessageHub>("/ForwardMessageHub");
                endpoints.MapHub<KePuBoxOnlineUser>("/KePuBoxOnlineUser");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=chart}/{action=Index}/{id?}");
            });
        }
    }
}

Содержание

  1. Error unprotecting the session cookie (in development and deployment) .Net Core 3.1 #25801
  2. Comments
  3. Asp.Net MVC Core: “Error unprotecting the session cookie” exception #2520
  4. Comments
  5. Error unprotecting the session cookie (in development and deployment) .Net Core 3.1 #25801
  6. Comments
  7. Error unprotecting the session cookie. #39091
  8. Comments
  9. An exception was thrown while deserializing the token. #2513
  10. Comments

Error unprotecting the session cookie (in development and deployment) .Net Core 3.1 #25801

In my startup.cs ,

I have added the «services.AddSession();» in ConfigureServices.

I have added the «app.UseSession();» in Configure

and then there’s «app.UseAuthorization();» in Configure by default

whenever I run it through assembly(dll file after publish) or in development mode.

The following error did happen ..

warn: Microsoft.AspNetCore.Session.SessionMiddleware[7]
Error unprotecting the session cookie.
System.Security.Cryptography.CryptographicException: The payload was invalid.
at Microsoft.AspNetCore.DataProtection.Managed.ManagedAuthenticatedEncryptor.Decrypt(ArraySegment 1 protectedPayload, ArraySegment 1 additionalAuthenticatedData)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

What can I do to solve this ?

The text was updated successfully, but these errors were encountered:

Источник

Asp.Net MVC Core: “Error unprotecting the session cookie” exception #2520

From @skorunka on Tuesday, November 29, 2016 6:02:13 AM

I have an Asp.NET MVC application with this Authentication setup:

When hosted in IIS, some users get this exception:

Web has only HTTPS binding, SSL certificate is ok and signed. What might cause this issue? What actually is that «key» value?

The text was updated successfully, but these errors were encountered:

From @skorunka on Thursday, December 1, 2016 1:51:57 AM

I can also see a lot of these:
11/30/2016 18:10:28:warn: Microsoft.AspNetCore.Session.DistributedSession[2]
Accessing expired session, Key:21d8f9ed-4013-2e65-d884-651a6f0060a0

From @kalluri-nb on Wednesday, December 14, 2016 7:22:31 PM

Any update on this. This is happening in cluster a lot. A session cookie value created on one instance is unable able to be unprotected by a different instance. Is there any basic setup for DataProtectionOptions for session management in cluster.

From @skorunka on Saturday, December 17, 2016 5:32:11 AM

The machine is not in a cluster or farm. Each requested is server by the same machine, by the same IIS site.

From @kalluri-nb on Saturday, December 17, 2016 3:00:44 PM

We resolved it by adding the redis as persistence store using DataProtectionBuilder.

From @skorunka on Sunday, December 18, 2016 3:54:36 AM

@kalluri-nb Nice, how can I resolve it? What should I change in the Setup.cs?

From @warrenfp on Tuesday, April 25, 2017 5:07:06 AM

@kalluri-nb: Can you share your implementation?

From @blowdart on Friday, April 28, 2017 12:36:41 PM

@skorunka Where are your keys being persisted? This is strange, it looks like the keyring can’t get created at all. Have you tried, as a stop gap, persisting the keyring to the file system anywhere?

From @skorunka on Tuesday, May 2, 2017 1:34:17 AM

@blowdart Hi, I’m using defaults. How can I setup where the keys are persisted? Or how can I know where they are actually persisted?

From @blowdart on Tuesday, May 2, 2017 10:43:04 AM

It tries to figure out the right place depending on machine configuration. The log files will tell you, if you’re logging at informational.

From @1amirjalai on Thursday, May 11, 2017 10:12:58 AM

@kalluri-nb what do you mean by

We resolved it by adding the redis as persistence store using DataProtectionBuilder.

could you please show an example?

From @1amirjalai on Thursday, May 11, 2017 10:16:37 AM

@blowdart may this issue an issue #228 are related

Closing due to lack of response.

Please reopen if you have further comments or questions on this issue.

This error started happening to me as well after my app was deployed in a docker container (through OpenShift, using RHEL s2i netcore 2.0 builder image https://github.com/redhat-developer/s2i-dotnetcore)
Running from VisualStudio17 was fine but my container is throwing these errors:

My app is a simple demo app that stores some strings to the session to reuse them later

+1 I see it too in random AppInisight traces. The app is similar to the one above, uses Session variables (no authentication though) and runs on mulitple VMs in Azure App Service. Seems like some configuration needs to be fixed ?

Thanks. Will try out the changes

I only have one node and still get this error

Do you have a stale cookie from a prior application? If you clear your cookies does it work?

We also see exceptions like this in Application Insights. I’m not able to replicate the issue, but we see it happening in the logs. We only have 1 instance and we use in memory sessions. Might it be because we swap staging with prod during releasing? Would moving session data out of the web process help? (Redis for example). We use the following version of the framework:

And here’s the exception:

System.Security.Cryptography.CryptographicException: The key was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

I looked at the source code and it seems that the exception is caught and it’s just a warning. However, it shows up in the Exceptions section of Application Insights and it’s a bit annoying because we get alerts when the exception rate is big enough. It’s caught, so it probably shouldn’t be logged this way in AI.

Well it can still indicate a problem, like an attacker trying to highjack a session, so it’s not unreasonable for it to get logged.

Yes, but we can’t do much about it and it generates noise. Logging as a warning is fine, but I think that Application Insights shouldn’t treat it as an exception.

Just wondering, is that warning reported when the user tries to make a request with a stale session id? For example, session expiration is 2h, but the user makes another request after 3h of inactivity, but without closing the browser? Such cases shouldn’t be reported at all I think.

Might the warning be caused by incorrect Data Protection settings? We’re using Azure App Services with a single instance, in memory sessions and default data protection settings, since we haven’t seen in the documentation any special settings being needed in that set up.

@mfronczyk A) we don’t track closed issues, please open a new issue.
B) This error is not caused by session storage or expiration issues, it’s caused by Data Protection mis-configuration or cross site cookie contamination. E.g. If your staging and production sites do not share encryption keys, or if you encryption keys aren’t being persisted across application restarts / redeploys.

Thanks for the tip — our staging and production slots do not share the encryption keys.

Источник

Error unprotecting the session cookie (in development and deployment) .Net Core 3.1 #25801

In my startup.cs ,

I have added the «services.AddSession();» in ConfigureServices.

I have added the «app.UseSession();» in Configure

and then there’s «app.UseAuthorization();» in Configure by default

whenever I run it through assembly(dll file after publish) or in development mode.

The following error did happen ..

warn: Microsoft.AspNetCore.Session.SessionMiddleware[7]
Error unprotecting the session cookie.
System.Security.Cryptography.CryptographicException: The payload was invalid.
at Microsoft.AspNetCore.DataProtection.Managed.ManagedAuthenticatedEncryptor.Decrypt(ArraySegment 1 protectedPayload, ArraySegment 1 additionalAuthenticatedData)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

What can I do to solve this ?

The text was updated successfully, but these errors were encountered:

Источник

Error unprotecting the session cookie. #39091

When I visit any of my web pages, as long as there is no session, he will prompt this. I don’t know how to cancel?

The text was updated successfully, but these errors were encountered:

Microsoft.AspNetCore.Session.SessionMiddleware[7]
Error unprotecting the session cookie.
System.Security.Cryptography.CryptographicException: The key <5564d4c5-567c-452a-b474-9689060415fe>was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

When you say «prompt this» what do you mean? It appears in the console log?

Where is your app hosted? Are there other data protection messages in the logs, especially around app startup time?

When you say «prompt this» what do you mean? It appears in the console log?

Where is your app hosted? Are there other data protection messages in the logs, especially around app startup time?

I checked that I may have residual cookies in the browser. After I empty it, it is normal. But I don’t know why this happens. There are previously expired sessions. This error will occur.

I really need log files and your hosting details to be of any help. It sounds like your data protection key ring is not persisted anywhere, so when an app restarts the key ring starts afresh and any existing cookies become invalid.

If the app was redeployed and generated new encryption keys then it won’t be able to decrypt old cookies. Those cookies will eventually be cleaned up by the client.

Hi @bbhxwl. We have added the «Needs: Author Feedback» label to this issue, which indicates that we have an open question for you before we can take further action. This issue will be closed automatically in 7 days if we do not hear back from you by then — please feel free to re-open it if you come back to this issue after that time.

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment. If it is closed, feel free to comment when you are able to provide the additional information and we will re-investigate.

Источник

An exception was thrown while deserializing the token. #2513

From @Tratcher on Saturday, April 29, 2017 6:54:00 AM

From @1amirjalai on April 29, 2017 13:30

System.Security.Cryptography.CryptographicException: The key was not found in the key ring.

Im running asp.net core on a webfarm using redis as dataprotection.
after getting error like this from redis
Timeout performing EVAL, inst: 9, queue: 1448, qu: 0, qs: 1448, qc: 0, wr: 0, wq: 0, in: 65536, ar: 0, clientName: xxxx
i opt in to make redis thread safe using this code

and initialize it in startup like :

but now i get new error

The antiforgery token could not be decrypted. —> System.Security.Cryptography.CryptographicException: The key was not found in the key ring.

I’m also getting this warning :

Error unprotecting the session cookie.

what should i do?

The text was updated successfully, but these errors were encountered:

From @1amirjalai on Saturday, April 29, 2017 7:21:51 PM

i also have opened an issue on stackoveflow here

From @blowdart on Monday, May 1, 2017 6:18:23 AM

Have you set the application name to be static?

From @1amirjalai on Monday, May 1, 2017 6:54:36 PM

@blowdart No i haven’t set application name to be static.

does setting application name to be static will affect my current users?

i have more info on what’s happened that cause this error. redis connection string has been changed accidentally for some minutes to another redis instance and again changed back to correct one.

here redis connection string was changed for some minutes under heavy website traffic
return ConnectionMultiplexer.Connect(«xxxxxx,abortConnect=false,syncTimeout=3000»);

i need a way to handle and prevent this error.

i was thinking about setting
.SetDefaultKeyLifetime(TimeSpan.FromDays(1));
for one day and again set it back to 90 days after two or three days if that could help prevent the errors.

but i’m affraid that it causes more error under current situation

From @1amirjalai on Monday, May 1, 2017 6:58:11 PM

Here are a list of errors and warnings that i’m getting constantly

The antiforgery token could not be decrypted. —> System.Security.Cryptography.CryptographicException: The key was not found in the key ring.
or
the most exception i get:
An exception was thrown while deserializing the token.
or
which i get the most warning is :
Error unprotecting the session cookie.

From @blowdart on Tuesday, May 2, 2017 10:42:22 AM

You’re going to find that 1 day is too little.

In your situation I’d start again. I’d set a static application name, because you do need that — keys are isolated by default based on app name. Redeploy and point everything to the same redis instance, and just take the hit of people being logged out. Remember unless you have redis configured for persistence the logout is going to happen whenever redis restarts too, because without persistence it’ll throw the keys away.

From @1amirjalai on Thursday, May 11, 2017 6:59:39 AM

@blowdart after setting the name i have new errors

An exception was thrown while deserializing the token.

From @blowdart on Thursday, May 11, 2017 7:19:38 AM

Hmm. Is there a full stack trace anywhere, because that’s not coming from data protection any more

From @1amirjalai on Thursday, May 11, 2017 9:55:14 AM

@blowdart yes here is one of them

and i also have a lot of warning

with the following full stack trace

From @blowdart on Thursday, May 11, 2017 10:19:39 AM

OK, throwing to a dev now to see if he can reproduce this. Hey @natemcmaster have a present 😀

From @1amirjalai on Sunday, May 14, 2017 7:31:20 AM

Antiforgery is configured at startup like :

can it be the reason of
System.Security.Cryptography.CryptographicException: The payload was invalid

any progress on the issue?

is there anything i can do to help this issue be solved?

From @1amirjalai on Monday, May 15, 2017 11:27:15 AM

weirdest thing happened as soon as i changed configed antiforgery token to just

all errors went away.

there are just unprotecting the session cookie warning that remained and no error

From @1amirjalai on Friday, August 11, 2017 2:30:27 AM

The issue has come back once again after upgrading servers.
again i’m having a lot of
Error unprotecting the session cookie.

System.Security.Cryptography.CryptographicException: The key was not found in the key ring. at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData) at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

is there any solution or workaround for this issue?

i have changed antiforgery cookie name and also changed application cookie name but no success

From @nickalbrecht on Thursday, August 17, 2017 12:42:42 PM

I ran into this today after publishing an update to a site running ASPNET Core 1.1 targeting .NET Framework 4.6.x. No redis involved. I get an error in my logs every 1-7 min, I’m assuming the interval is tied to user activity. None of the users have reported any problems using the app yet, though oddly enough, none of these error seem to be captured in Application Insights.

I’m just using very basic Cookie Authentication

From @eriksendc on Friday, December 8, 2017 12:50:53 PM

For a while now (most of this year) we’ve been seeing the following in our logs.

I believe these are related, but I never know because the stdout logs don’t have a timestamp. Anyways, we get anywhere between 200 and 400 of these a day. getyourpet.com has about 7000-8000 sessions a day (Google Analytics sessions). We haven’t received any support requests that seem to tie to not being able to submit a particular form.

We’ve been wondering if these are related to some kind of authentication time out (like if people have stale browsers and then click on something) or if there are specific forms on our site that have issues. We know that we have way more total form posts than the 200-400 errors observed per day.

Any suggestion on how to get started digging in to this? If this is sort of a normal thing, then I’ll continue to ignore them.

Thanks in advance for any pointers. I put this here because I Googled around a lot and this seemed to be the closest matching issue. Let me know if I should open a different issue.

Thanks,
-Brian Eriksen

From @Tratcher on Friday, December 8, 2017 1:37:37 PM

The encryption is based solely on server state, there’s no user login involved. If the tokens can’t be decrypted then either one of two things is happening:

  1. Your encryption keys aren’t being persisted across app restarts and the client is sending you a token from the prior instance of your app. You should get warnings about this in your logs when the application starts.
  2. You have your app running on two or more nodes that aren’t sharing the same encryption keys. See https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?tabs=aspnetcore2x for configuring multiple nodes.

From @eriksendc on Saturday, December 9, 2017 7:15:32 AM

As always, thanks for your quick response!

Re 2, we are only running on a single web server (but some day we will run on multiple servers, so thanks for that link).

I guess it’s zebras not horses. What’s the next thing to try?

Again, thanks so much in advance!!

From @Tratcher on Monday, December 11, 2017 9:35:18 AM

If you have a repro you can set your log level to Trace to get more information about what DataProtection thinks is wrong. You should be able to create a repro by capturing the headers from a failing request.

From @GrabYourPitchforks on Monday, December 11, 2017 11:59:33 AM

Источник

User1879745236 posted

When trying to run my ASP.NET Core website it crashes while trying to create a directory in C:WINDOWSsystem32configsystemprofile.

1. Why is that even necessary?

2. What components/features might require this?
I’m not using anything that might need it, from a feature like
FileDataStore I can understand it.

3. I’ve tried turning off all kinds of features activated in the startup.cs, the same error remains or hosting breaks entirely.

4. I’ve tried granting IIS_USRS write access to the folder. However this is not a real solution as I cannot tell my customers that my hosted website requires access to the system32 folder. It also makes no sense for .NET Core. Which is supposed to be platform
independent and all. Yet it requires access to a hardcoded file path?!

5. I want to list all the features being used. The Startup.cs calls several other files. So in order to keep it readable I flattened the code and simplified some of the names. It could be that a compiler error sneaked in because of that. But the actual code
compiles fine.:

using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Company.Features; namespace Company.WebSite {   public class Startup {     private IConfiguration m_Configuration;     public IConfiguration Configuration { get { return m_Configuration; } }     public Startup (IConfiguration configuration) {       m_Configuration = configuration;     } // Constructor Startup     public void ConfigureServices (IServiceCollection services) {       IConfigurationSection root = Configuration.GetSection(MyOptions.OptionsKey);       MyOptions options = root.Get<MyOptions>();       services.Configure<MyOptions>(root);       services.TryAddTransient<ForwardTokenHandler>();       IHttpClientBuilder blClientBuilder = services.AddHttpClient(MyWebApiClient.ClientName);       blClientBuilder.ConfigurePrimaryHttpMessageHandler(serviceProvider => {         return new HttpClientHandler() {           AllowAutoRedirect = false,           PreAuthenticate = true,           UseDefaultCredentials = true,         };       });       blClientBuilder.AddHttpMessageHandler<ForwardTokenHandler>();       services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromDays(2));       IDataProtectionBuilder dataProtectionBuilder = services.AddDataProtection();       DataProtectionOptions dataProtectionOptions = root.GetSection(DataProtectionOptions.OptionsKey).Get<DataProtectionOptions>();       if (dataProtectionOptions != null) {         if (!String.IsNullOrWhiteSpace(dataProtectionOptions.KeyRingFolder) && Directory.Exists(dataProtectionOptions.KeyRingFolder)) {           // This would be a candidate for requiring file system access so I tried commenting out this line.           dataProtectionBuilder.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionOptions.KeyRingFolder));           dataProtectionBuilder.ProtectKeysWithDpapi(true);         }         if (!String.IsNullOrWhiteSpace(dataProtectionOptions.ApplicationName)) {           dataProtectionBuilder.SetApplicationName(dataProtectionOptions.ApplicationName);         }       }       WebSessionStateOptions sessionStateOptions = root.GetSection(sessionStateOptions.OptionsKey).Get<sessionStateOptions>();       if (sessionStateOptions == null) {         sessionStateOptions = new WebSessionStateOptions();         sessionStateOptions.Cookie.Name = ".Company.WebSession";       }       services.AddSession(options => {         options.IdleTimeout = TimeSpan.FromMinutes(20);       });       IConfigurationSection securitySection = configuration.GetSection(SecurityClientOptions.OptionsKey);       SecurityClientOptions securityOptions = securitySection.Get<SecurityClientOptions>();       services.Configure<SecurityClientOptions>(securitySection);       services.AddHttpContextAccessor();       IConfigurationSection securitySection = configuration.GetSection(SecurityClientOptions.OptionsKey);       SecurityClientOptions securityOptions = securitySection.Get<SecurityClientOptions>();       if (securityOptions.AuthenticationType == AuthenticationType.Windows) {         // Potential cause of file system problems, tried commenting it out.         services.AddTransient<ITokenStorage, CookieTokenStorage>(serviceProvider => {           IHttpContextAccessor contextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();           return new CookieTokenStorage(contextAccessor);         });       } else if (securityOptions.AuthenticationType == AuthenticationType.Cookies) {         CookieAuthenticationOptions cookieOptions = securitySection.GetSection(CookieAuthenticationOptions.OptionsKey).Get<CookieAuthenticationOptions>();         if (cookieOptions != null) {           services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => {             options.Cookie.Name = cookieOptions.Cookie.Name;           });         }         // Potential cause of file system problems, tried commenting it out.         services.AddTransient<ITokenStorage, ClaimsTokenStorage>();       }       services.AddTransient<MyWebApiClient>();       services.AddTransient<ConfigController>();       IMvcBuilder mvcBuilder = services.AddControllersWithViews();       services.AddAntiforgery();       if (services == null) { throw new ArgumentNullException(nameof(services)); }       services.TryAddTransient<SessionIdHandler>();       services.TryAddTransient<ForwardTokenHandler>();       IHttpClientBuilder builder = services.AddHttpClient("SecurityApiClient");       builder.ConfigurePrimaryHttpMessageHandler(serviceProvider => {         return new HttpClientHandler() {         };       });       builder.AddHttpMessageHandler<SessionIdHandler>();       builder.AddHttpMessageHandler<ForwardTokenHandler>();       services.TryAddTransient<JwtTokenService>();       CookieEncryption.Initialize(securityOptions.CookieEncryptionKey);       return services;     } // ConfigureClientSecurity     public void Configure (IApplicationBuilder appIWebHostEnvironment env) {       if (env.IsDevelopment()) {         app.UseDeveloperExceptionPage();       } else {         app.UseExceptionHandler("/Home/Error");         app.UseHsts();       }       app.UseStaticFiles(); // Tried commenting this out.       app.UseRouting();       app.UseAuthentication();       app.UseAuthorization();       app.UseSession();       app.UseEndpoints(endpoints => {         endpoints.MapControllerRoute(           name"Default",           pattern"{controller=Home}/{action=Index}");       });     }   } }

Edit 1:
6. The full error from browser:

HTTP Error 500.31 — ANCM Failed to Find Native Dependencies

Common solutions to this issue:

The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.

Specific error detected by ANCM:

System.UnauthorizedAccessException: Access to the path ‘C:WINDOWSsystem32configsystemprofile.dotnet’ is denied. at System.IO.FileSystem.CreateDirectory(String fullPath, Byte[] securityDescriptor) at System.IO.Directory.CreateDirectory(String path)
at Microsoft.Extensions.EnvironmentAbstractions.DirectoryWrapper.CreateDirectory(String path) at Microsoft.DotNet.Configurer.FileSystemExtensions.<>c__DisplayClass0_0.b__0() at Microsoft.DotNet.Cli.Utils.FileAccessRetrier.RetryOnIOException(Action action)
at Microsoft.DotNet.Configurer.FileSystemExtensions.CreateIfNotExists(IFileSystem fileSystem, String filePath) at Microsoft.DotNet.Configurer.FileSentinel.Create() at Microsoft.DotNet.Configurer.DotnetFirstTimeUseConfigurer.Configure() at Microsoft.DotNet.Cli.Program.ConfigureDotNetForFirstTimeUse(IFirstTimeUseNoticeSentinel
firstTimeUseNoticeSentinel, IAspNetCertificateSentinel aspNetCertificateSentinel, IFileSentinel toolPathSentinel, Boolean isDotnetBeingInvokedFromNativeInstaller, DotnetFirstRunConfiguration dotnetFirstRunConfiguration, IEnvironmentProvider environmentProvider)
at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry telemetryClient) at Microsoft.DotNet.Cli.Program.Main(String[] args)

7. Event viewer error (there are three, but this is the only one with relevant information):

Could not find ‘aspnetcorev2_inprocess.dll’. Exception message:
System.UnauthorizedAccessException: Access to the path ‘C:WINDOWSsystem32configsystemprofile.dotnet’ is denied.
   at System.IO.FileSystem.CreateDirectory(String fullPath, Byte[] securityDescriptor)
   at System.IO.Directory.CreateDirectory(String path)
   at Microsoft.Extensions.EnvironmentAbstractions.DirectoryWrapper.CreateDirectory(String path)
   at Microsoft.DotNet.Configurer.FileSystemExtensions.<>c__DisplayClass0_0.<CreateIfNotExists>b__0()
   at Microsoft.DotNet.Cli.Utils.FileAccessRetrier.RetryOnIOException(Action action)
   at Microsoft.DotNet.Configurer.FileSystemExtensions.CreateIfNotExists(IFileSystem fileSystem, String filePath)
   at Microsoft.DotNet.Configurer.FileSentinel.Create()
   at Microsoft.DotNet.Configurer.DotnetFirstTimeUseConfigurer.Configure()
   at Microsoft.DotNet.Cli.Program.ConfigureDotNetForFirstTimeUse(IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel, IAspNetCertificateSentinel aspNetCertificateSentinel, IFileSentinel toolPathSentinel, Boolean isDotnetBeingInvokedFromNativeInstaller,
DotnetFirstRunConfiguration dotnetFirstRunConfiguration, IEnvironmentProvider environmentProvider)
   at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry telemetryClient)
   at Microsoft.DotNet.Cli.Program.Main(String[] args)

Edit 2:

It turns out the arguments reference in my Web.Config to the compiled project file had the wrong name. I renamed it but the site still doesn’t work. It’s annoying that we get these random errors unrelated to the actual problem. I don’t get an error message
any more, only a warning in the Event Viewer:

Error unprotecting the session cookie.

Exception: 

System.Security.Cryptography.CryptographicException: The key {GUID} was not found in the key ring.

This is very strange as the cookie protection shouldn’t be used because the settings aren’t there. So the real error is probably something completely different. As with the other error.

How to Resolve ASP.NET Core Key Protection Ring Problem in AWS Lambda

Introduction

When it comes to server less web application design using asp.net core razor pages, we definitely need to consider a factor of data protection key management and its lifetime in asp.net core. I developed a site using AWS toolkit of ASP.NET Core Razor Pages. The main advantage of ASP.NET Core is cross-platform from where we can deploy our application in MAC, Linux or windows. I deployed my site initially in IIS Server from which I got the results as expected .but later period I decided to host my site in AWS Lambda in order to meet our client requirement. Strangely, I got unexpected behavior from my site. I just refer the cloud information Lambda Log to identify or pinpoint the case, I got the error Information like “Error Unprotecting the session cookie” from the log. In this article, I tried to explain the root cause of the problem and its solution to overcome such kind of issue.

This is feature in ASP.NET Core which acts as replacement for Machine Key element in order to support modern web applications, this act as cryptographic API to developers. What makes the difference from old cryptographic mechanism is that we can embed our own cryptographic mechanisms. So that encryption and decryption of data will act according to the specified cryptographic mechanisms in our application else takes default on its own.

When an application runs, the data protection for that system will be set by default on the basis of operating system.

The web application has its own key ring which is highly secured and this will appropriate to the single machine. If our application is sp

read across the machine and definitely we will have different scene in order to store Key storage location. We have various methods to handle this situation   which are as follows

  • Ephemeral storage (In-Memory, short live)
  • SQL Server
  • Redis
  • Azure storage 
  • File System
  • Windows Registry(Only IIS  or windows deployments)

In above mentioned methods, Ephemeral storage is not suit for web farm scenarios. In that occasion, we can choose SQL Server, Redis, Azure storage or File System (Shared Network) to store the Key Storage. So that Load balancer will take no effect on Data Protection without problem.

The stunning feature of data protection mechanism is that the Key that is generated which is automatically handled by itself which has an lifetime of 90 days .once it’s expired it will automatically spin-off.

The application will chooses the default key from the key ring and new keys will be generated once the existing is expired. The default expiration date of key is 90 days or else we can configure it in our application like this in our startup class of ASP.NET core


        services.AddDataProtection()
       // use 14-day lifetime instead of 90-day lifetime
       .SetDefaultKeyLifetime(TimeSpan.FromDays(14));


Issue Scenario

ASP.NET Core Razor Pages is hosted in AWS Lambda. When navigate from one page to another page for the first time, we got 400 responses Error because the request is not accepted by anti-forgery token. Hence I tried it second time and it is working as expected. I was scratching my head for week to address this issue. I have tried various approaches to find a solution, which I have explained in detail

Approach 1 – Disable Anti-forgery Token

I know this is a bad idea, but I was clueless and so I did disabling anti forgery token and 400 bad request error disguised, then I didn’t get any values from tempdata . When I checked the cloud information log , then  I got some information from request log as below


[Warning] Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository: Using an in-memory repository. Keys will not be persisted to storage.
[Warning] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager: Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
[Information] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager: Creating key {fbf9442c-a80b-43c0-b898-16f94d1d532b} with creation date 2019-07-30 12:23:07Z, activation date 2019-07-30 12:23:07Z, and expiration date 2019-10-28 12:23:07Z.
[Warning] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager: No XML encryptor configured. Key {fbf9442c-a80b-43c0-b898-16f94d1d532b} may be persisted to storage in unencrypted form.
[Warning] Microsoft.AspNetCore.Session.SessionMiddleware: Error unprotecting the session cookie.


Approach 2 – Using Redis Cache

It is very important to note the data protection in lambda of razor pages. It is cryptographic mechanism in which all cookies related information and anti-forgery tokens will be encrypted by the system generated key in asp.net core and the same key will be used to decrypt the information. In ASP.NET Core there are various key storage locations as explained above. By default, keys will be stored in Windows Registry in IIS Server but in the Lambda, the scene is different .because there are no windows registry will be there and so we are getting such error like “Error in Unprotecting the session cookie”

In ASP.NET Core data protection terms, Protected means encryption and Unprotected means decryption. It is clearly describing that there is error in Unprotecting or decrypting the session cookie. In Lambda as there is no persistence storage instead it will be using ephemeral key repository which will be challenge to lambda in storing protection key which is inevitable.

Handling in-memory Session Data in Redis

In order to implement the redis cache session management, we need to install the extension of distributed redis cache using nugget manager as follows

Then we must update the services with distributed redis cache in startup.cs in asp.net core

Once you have configured the distributed redis cache then we must use Use session middleware, then session management of lambda will be stored in redis cache.

Handling Protection Key in IXmlRepository

Lot of Key storage location are available but we decided to store persistence key storage location as Mysql, certainly we can do this by entity framework core. Let’s see how we can implement this in action.

First, we have to design the POCO Class of DataProtection Key


    public class DataProtectionKey
    {
        [Key]
        public string FriendlyName { get; set; }
        public string XmlData { get; set; }
    }


Next, we need to implement the IXmlrepository which will be as follows


   public class DataProtectionKeyRepository : IXmlRepository
    {
        private readonly AppDbContext _db;

        public DataProtectionKeyRepository(AppDbContext db)
        {
            _db = db;
        }

        public IReadOnlyCollection GetAllElements()
        {
            return new ReadOnlyCollection(_db.DataProtectionKeys.Select(k => XElement.Parse(k.XmlData)).ToList());
        }

        public void StoreElement(XElement element, string friendlyName)
        {
            var entity = _db.DataProtectionKeys.SingleOrDefault(k => k.FriendlyName == friendlyName);
            if (null != entity)
            {
                entity.XmlData = element.ToString();
                _db.DataProtectionKeys.Update(entity);
            }
            else
            {
                _db.DataProtectionKeys.Add(new DataProtectionKey
                {
                    FriendlyName = friendlyName,
                    XmlData = element.ToString()
                });
            }

            _db.SaveChanges();
        }
    }


In order to initiate connection between portal and Mysql database we must implement AppDbContext


public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions options) : base(options) { }

        public DbSet DataProtectionKeys { get; set; }
    }


Finally, we must include AppDBContext and Custom Key XMLRepository in startup.cs as follows,

Startup.cs


namespace MyPortal.Web
{
    public class Startup
    {      

        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;         

        }

        public  IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration["mysqlconnection:connectionString"].ToString();
            services.AddDbContext(o => o.UseMySQL(connectionString));

            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.Configure(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            services.AddSingleton();
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

            services.AddSingleton();

            //services.AddMemoryCache();
            var built = services.BuildServiceProvider();
            services.AddDataProtection().AddKeyManagementOptions(options => options.XmlRepository = built.GetService());

            services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = "redisinstancename";
                options.Configuration = "redishIp:portNo";
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());


            services.AddSession(opt =>
            {
                opt.Cookie.IsEssential = true;
                opt.IdleTimeout = TimeSpan.FromHours(1);
            });


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseDeveloperExceptionPage();

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            // app.UseMvc();
            app.UseSession();
            app.UseCookiePolicy();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Feedback", action = "Create" });
            });
           
           
        }
    }
}


Note, to use MySQL as your repository, we must include the Entity framework core package for MySQL

Conclusion

Once you have configured the Persistence storage for protection key as MySQL. All error on Unprotecting session cookie disguised and my application works fine without any issues. I think this article is helpful to you in resolving the persistence storage issue. If any feedback, please comment which will be helpful for me to shape the article in best way.

using InnoADLMedicalWeb.Areas.KePuBox.Controllers;
using InnoADLMedicalWeb.Areas.SportsDoctorAPI.Controllers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.IO;
using InnoADLMedicalWeb.Code.Hub;

namespace InnoADLMedicalWeb
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
            services.AddSession((options) =>
            {
                // 设置 Session 过期时间
                options.IdleTimeout = TimeSpan.FromHours(24);
            });
            services.AddHttpContextAccessor();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddCors(op =>
            {
                op.AddPolicy("AllowAll", builder =>
                {
                    builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                });
            });

            //services.AddCors(c =>

            //  c.AddPolicy("AllowAll", p =>
            //  {
            //      p.AllowAnyOrigin();
            //      p.AllowAnyMethod();
            //      p.AllowAnyHeader();
            //  })
            //  );

            // 添加Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "API",
                    Version = "v1",
                    Contact = new OpenApiContact()
                    {
                        Name = "binbin",
                        Email = "admin@bbhxwl.com"
                    }
                });
                c.SwaggerDoc("unity", new OpenApiInfo
                {
                    Title = "API",
                    Version = "v1",
                });
                try
                {
                    // 获取xml文件名
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    // 获取xml文件路径
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    // 添加控制器层注释,true表示显示控制器注释
                    c.IncludeXmlComments(xmlPath, true);
                }
                catch (Exception)
                {

                }
            });
            services.AddControllersWithViews().AddNewtonsoftJson(options =>
            {

                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;  // 设置时区为 UTC)
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            }).AddJsonOptions(config =>
            {
                config.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            services.AddRazorPages().AddRazorRuntimeCompilation();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseWebSockets();
            app.UseCors("AllowAll");
            app.UseStaticFiles();
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto
            });
            app.UseRouting();
            app.UseSession();
            app.UseAuthorization();
           
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                if (!env.IsDevelopment())
                {
                    c.InjectStylesheet("/css/swaggercustom.css");
                }
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "EnterpriseAPI");
                c.SwaggerEndpoint("/swagger/unity/swagger.json", "unity");
            });
           
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapAreaControllerRoute("areas", "AgentManage", "{area:exists}/{controller=Login}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "KePuBox", "{area:exists}/{controller=Login}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "SportsDoctorAPI", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "ResourceCenter", "{area:exists}/{controller=ResourceList}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "api", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute("areas", "EnterpriseAPI", "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapHub<TongXunHub>("/TongXunHub");
                endpoints.MapHub<ForwardMessageHub>("/ForwardMessageHub");
                endpoints.MapHub<KePuBoxOnlineUser>("/KePuBoxOnlineUser");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=chart}/{action=Index}/{id?}");
            });
        }
    }
}

bbhxwl

Error unprotecting the session cookie.

When I visit any of my web pages, as long as there is no session, he will prompt this. I don’t know how to cancel?

bbhxwl

Microsoft.AspNetCore.Session.SessionMiddleware[7]
Error unprotecting the session cookie.
System.Security.Cryptography.CryptographicException: The key {5564d4c5-567c-452a-b474-9689060415fe} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

blowdart

When you say «prompt this» what do you mean? It appears in the console log?

Where is your app hosted? Are there other data protection messages in the logs, especially around app startup time?

bbhxwl

When you say «prompt this» what do you mean? It appears in the console log?

Where is your app hosted? Are there other data protection messages in the logs, especially around app startup time?

I checked that I may have residual cookies in the browser. After I empty it, it is normal. But I don’t know why this happens. There are previously expired sessions. This error will occur.

blowdart

I really need log files and your hosting details to be of any help. It sounds like your data protection key ring is not persisted anywhere, so when an app restarts the key ring starts afresh and any existing cookies become invalid.

Tratcher

msftbot

Hi @bbhxwl. We have added the «Needs: Author Feedback» label to this issue, which indicates that we have an open question for you before we can take further action. This issue will be closed automatically in 7 days if we do not hear back from you by then — please feel free to re-open it if you come back to this issue after that time.

msftbot

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment. If it is closed, feel free to comment when you are able to provide the additional information and we will re-investigate.

See our Issue Management Policies for more information.

Понравилась статья? Поделить с друзьями:
  • Error unpacking of archive failed cpio bad magic
  • Error unnecessary else after return no else return
  • Error unmounting dev sda1 target is busy udisks error quark 14
  • Error unmounting dev nvme0n1p3
  • Error unmarshalling return nested exception is