Validation of viewstate MAC failed- Server Error in '/' Application - c#

I got this error when i access my hosted web application(in VS2008 C# ASP.NET 3.5 Framework)
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
The interesting thing is that there is no problem if we continue after login process. If you logged in and do nothing for 15 or 20 minutes, then click any menu...this error will be generated. So I doubt that it is related to session out. In my webconfig file I have written session time out as follows.
<sessionState timeout="15" />
How can I correct this error?

There are a few ways to fix this issue, but some solutions are better than others. The fastest way is usually to add the following to the web.config:
<pages enableEventValidation="false" viewStateEncryptionMode="Never">
The problem with the above solution is that you sacrifice some security. The next "quick fix" is to add the following to the web.config, but there are drawbacks to this as well:
<pages enableViewStateMac="false">
If this application is hosted by a web farm or is otherwise distributed across multiple web servers, you should probably steer clear of that option.
In my opinion, the best overall solution is offered here.

I believe that your problem is in App Pool "Idle timeout" field.
You have to ask to your provider to change it to something greater... say 20mins
Take a look here.

Related

.Net Core 2.x User Session signs out on Shared Hosting unexpectedly

I am playing around with aspnetboilerplate.com's template for dotnet core. What I am trying to do is to deploy the template on a shared hosting (windows) server running Plesk (note, I have no control over the server at all).
The template works perfect locally, can log in, add users, roles, etc. Deploying it the shared hosting server gave some issues, but that was resolved relative quickly (configuring for dotnet core and had to drop to dotnet core 2.1 as 2.2 is not yet supported on the server).
The problem now is after logging in, within a minute I re-directed to the login page. I have had a similar problem with ASP.NET MVC5, but providing a Machine Key in the web.config and making use of a database for session data fixed that problem. So I am reasoning it is the same problem with the dotnet application.
But seeing as dotnet core does not use machine keys and DataProtectionApis a different approach is needed.
So I have tried adding services.AddDataProtection(); to StartUp.Configure()
I have read Distributed caching in ASP.NET Core and just about all the links coming off there as well as tried multiple code examples, but either I do not know what I am doing (high probability) or I am not doing something right.
So, how do I prevent the user being signed out unexpectedly using dotnet core 2.1 on a shared hosting server?
EDIT - 2019-01-25
Some new information: Tried setting timeouts as suggested, but this either does nothing or is not possible. For the dotnet application to run on Plesk, I had to disable ASP.NET support so that .NET core gets No Managed Code Application Pool. Trying to access ASP.Net settings on Plesk the (where you'd have access to Application Pool setting, etc) gives an error saying 'ASP.NET support is switched off for this website'.
One thing that does not happen is the App_Data/Logs folder never gets created when publishing. I had to manually create and set permissions so that log4net can create a log file. The log file provided me with additional information:
ERROR 2019-01-25 09:33:03,005 [6 ] .Antiforgery.Internal.DefaultAntiforgery - An exception was thrown while deserializing the token.
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} was not found in the key ring.
Searching for this error only once again lead me to documentation about adding services.AddDataProtection() to the ConfigureServices method, but this drones on about Azure Key Vaults (or other external providers) or writing info to a shared UNC so that other servers can access cached key info (and this is probably what I need). But seeing as all of these options are not available to me, I found an extension method which allows the key to be stored on an MSSQL server. Busy setting this up now to test.
If anybody wants to give their opinion, please be my guest.
UPDATE 2 - 2019-01-25 - SUCCESS (for now)
It would appear that making use of DataProtectionAPI is the way to go. Logs are not reporting any AntiforgeryValidationException, yet. I am going to let it run for a while and if all is good, I'll post the solution and how it has been implemented.
Based off the information you provided above, I believe your session is timing out.
When the session times out the user will be redirected to the login page to reauthenticate. I am not overly familiar with plesk but from very quick googling it seems that you should be able to increase the session timeout.
Of course, if you are setting the sessiontimeout yourself in configurservices you could just adjust it there as well I would assume (again unfamiliar with the plesk setup fully).
If you do that, the problem should resolve itself. Perhaps the session timeout is set to a short time period for testing?
.net session state
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
As PersistKeysToSqlServer is not supported in dot net core 3.1, we can use .PersistKeysToDbContext<AppDBContext>() or PersistKeysToFileSystem as it is shown here.
The problem, it turns out was not the session expiring, but rather, when another server takes over the load of the my site, it has no session context. Data Protection services allows for the creation of a database to store session info in and it shared across servers in the farm. Similar to the session state attribute from web.config in MVC projects:
<sessionState mode="SQLServer" sqlConnectionString="Data Source=000.000.000.000;Initial Catalog=session_db;User Id=user;Password=password;" allowCustomSqlDatabase="true" timeout="480" />
This is how I solved the problem:
Within ConfigureServices I added:
services.AddDataProtection()
.SetApplicationName("MyApplicationName")
.SetDefaultKeyLifetime(TimeSpan.FromDays(14))
.PersistKeysToSqlServer(_config["DataProtection:SqlServerConnectionString"]);
I also had to create a separate database which is responsible for storing the session information. The DataProtextion:SqlServerConnectionString is an entry in the appsettings.json file:
"DataProtection":
{
"SqlServerConnectionString": "Server=server; Database=database; User=user; Password=password;"
}
There are ways to probably solve this problem (eg with Redis), but seeing as I have no control over the server my site is hosted on, Data Protection services works just fine.

Getting account errors on remote server only - Antiforgery and AppData write permissions ASP.NET MVC

I guess I'm not understanding how the account (login/register) works in MVC. On the dev server everything works fine. When I deploy my application I get a couple errors:
Access denied creating App_Data subdirectory
and
The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.
I can fix the first error by enabling write permissions on the remote server, but everytime I publish it reverts permissions. I didn't think I was using an sqlexpress anywhere in my app because my connection strings are for SQL server 2012 databases, but I'm not sure if MVC will create one just for the account controls, see connection strings below:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=MANDRAKE.arvixe.com;Initial Catalog=DB1Name;Integrated Security=False;User Id=Username;Password=***;MultipleActiveResultSets=True" />
<add name="BudgetingEntities" connectionString="metadata=res://*/Models.BudgetModel.csdl|res://*/Models.BudgetModel.ssdl|res://*/Models.BudgetModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MANDRAKE.arvixe.com;initial catalog=DB2Name;user id=Username;password=***;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Another thing to note is I originally had this set up on my arvixe server as one website, and then I added a domain and published to that domain. That is when the problems happened, but I don't see how that would be correlated. I also added a captcha control to the user registration page, but when I remove that code, the errors persist.
Any ideas would be helpful, I don't know if I need to explicitly set the machinekey configuration (I didn't have to do that before, so I don't think I need to).
Just for anyone's information it had to do with my user account on the arvixe server I have. I don't know exactly what they did, but they told me that the permissions got messed up somehow. I'm still unsure exactly what is going on. I was trying to implement a captcha function but it seemed to mess everything up, possibly because the tutorials were outdated on how to add captcha to an ASP.NET MVC project.

Validation of viewstate MAC failed. - ASP.net

I have an C# ASP.net website hosted with www.blacknight.com.
Sometimes when I login to my website I get the following error:
This happens in about 1 in ever 10 login attempts. I have contacted them and they assured me that its not hosted on a Web Farm or cluster and to check my ViewState.
Does anyone know what could be wrong here? I cant reproduce it everytime so its hard to track down.
Please see the KB article at http://support.microsoft.com/kb/2915218 for a resolution to this issue. In particular, you should set an explicit <machineKey> element in Web.config.
Appendix A of that article tells you how to generate a <machineKey> element.
Never set EnableViewStateMac=false. And you should never use a key that you got from a third-party generator. Only use one that you generated yourself.
Is it possible that IIS is recycling your application between the original page load, and the login attempt? If you don't specify a <machinekey /> in the web.config, a new machine key will be generated on application start up. And then, when you attempt to validate the viewstate that was generated on the old machine key during post back, this exception would be thrown.

Context.User.Identity.GetUserName() for 2 website is accesing same user

I have created 2 webapplication in Visual Studio 2013 using C#.
I have registered 2 new users in both the applications.
Now if I run both the application in Google Chrome. I am getting the following;-
1) If I login in one website and if I refresh the other website page. It is also logged in.
How can i make it seperate, so that both can have there seperate users?
Has it someting to do with Context.User.Identity, are both site using same cookies??
Please help me in understanding it.
Thanks
Assuming you haven't explicitly changed the authentication configuration in the web.config across both websites, then the behaviour you are seeing is by design.
To configure forms authentication across applications, you set attributes of the forms and machineKey sections of the Web.config file to the same values for all applications that are participating in shared forms authentication.
...Unless otherwise noted, the name, protection, path, validationKey, validation, decryptionKey, and decryption attributes must be identical across all applications.
So, if you want an independent ticket for each site, the easiest solution would be to give each site it's own distinct ticket name
<forms name=".ASPXFORMSAUTH_SITEA" ... />
<forms name=".ASPXFORMSAUTH_SITEB" ... />
For security purposes, you might also want to consider using different encryption/decryption keys as well.
You can make the logins seperate by doing the following (my guess is that you want the sessions seperate as well), which Microsoft advise to do if running multiple websites from a web server, most likely to avoid this cross cookie issue...
In your web.config give the session and the authentication cookies unique names, e.g.
<sessionState cookieName="UNIQUESESSION1" timeout="20"/>
and
<forms timeout="2880" name="UNIQUEAUTH1" />

Use of StateServer with C# Website?

I've got two web portals that are almost identical in architecture. One requires that I add the following to my web.config and enabling the state server, as the logged-in user sessions expire after 2-5 seconds:
<sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424"
cookieless="false"
timeout="20"/>
I'd like to know what some of the root-causes are that will cause this issue in one web portal but not the other.
This is a C# ASP.Net v3.5 app sitting on Windows 2008 R2.
Strangely enough, on my local dev box (Windows 7), I don't need to enable this, and the sessions last just fine.
Any discussion on this would be appreciated.
You also need to make sure that you define a machine key, in your servers in the machine.config files, or in your web.config.
I've implemented this scenario successfully on my work servers in a web farm scenario, most recently last week, and it has definitely helped maintain my sessions.
As to why you need to do this ---
The client needs a way to track their session ID. In a farm scenario, depending on traffic, they can be bounced from Server #1 on one page request, to Server #2 on another page request, then back to Server #1 on yet another page request.
This link is pretty helpful.

Categories