"Key not valid for use in specified state" Error for .Net 4.5 MVC 4 Application - asp.net-mvc-4

To preface this question, please excuse me if I am getting any of my terminology wrong. The technology is very new to me.
I have a website in MVC 4, .Net 4.5 built with VS 2012 hosted on IIS7 and have used the "Identity and Access" wizard to configure authentication using a business identity provider. I have entered a path to an STS metadata document similar to:
https://xyz.mycompany.com/app/FederationMetadata/2007-06/FederationMetadata.xml
The site is currently hosted under three different realms. The first is my local development environment, second is standard integration testing and third is development.
http://localhost/myapp
http://sit.mycompanytest.com/myapp
http://dev.mycompanytest.com/myapp
It is important to note that the "dev" sub-domain is in a web farm or load balanced or something. I do not currently know the exact details of the load balancing architecture.
When I navigate to any of the above sites using IE 10 I am redirected to a login screen where I enter my credentials and gain access to the given site.
But, on the "dev" sub-domain, when navigating around the site using links and form submissions I eventually will get the following error:
Key not valid for use in specified state.
The stack trace of the error is:
[CryptographicException: Key not valid for use in specified state.]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +397
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +90
[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +1158198
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +173
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +756
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +100
System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +668
System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +164
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +173
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I suspect the error is happening when the load balancer changes servers.
And, have been considering the 2nd workaround solution from the following web site: (http://blogs.msdn.com/b/distributedservices/archive/2012/10/29/wif-1-0-id1073-a-cryptographicexception-occurred-when-attempting-to-decrypt-the-cookie-using-the-protecteddata-api.aspx). But, the web site states that the solution is for .Net 4.0.
Will that solution work for .Net 4.5? And, if not, how can I fix the error?

I was able to fix the error by following the instructions in the following post by Vittorio Bertocci:
http://www.cloudidentity.com/blog/2013/01/28/running-wif-based-apps-in-windows-azure-web-sites-4/
Basically, I had to enable web farm cookies using the Identity and Access Tool.
In VS 2012, right click the project > select Identity Access > select the Configuration tab > check the Enable web farm ready cookies check box > click OK

IMHO the loadbalancing is the problem. You have to make sure the farm shares the same machine key. This can be done at machine level or in the web.config of your application.

Deleting the FedAuth cookies might work. When the exception occurs, try this in the Application_Error method of the Global.asax file:
Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut();

Related

Blazor throwing error when using HttpContext

I want to get current windows user name when user opens the website. My application uses Blazor server-side. To get current username, I added:
In startup.cs:
services.AddHttpContextAccessor(); (under
ConfigureServices)
In razor page:
#inject IHttpContextAccessor httpContextAccessor
In razor page method:
string userName = httpContextAccessor.HttpContext.User.Identity.Name;
When I execute the code, the application throws an exception:
"An error has occurred. This application may no longer respond until reloaded."
I get this error only when I deploy on IIS. On local machine it works well.
I had a similar issue trying to access HttpContext for user information using Blazor. I found this here which was a life saver. HttpContext is NULL when running web app in IIS
All I had to do to solve the problem was to enable WebSockets in IIS.
Here are the steps: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1#iisiis-express-support
If you were to change that string from
string userName = httpContextAccessor.HttpContext.User.Identity.Name
to
string userName = httpContextAccessor?.HttpContext?.User?.Identity?.Name??"Anonymous"
then it would probably work.
It's because your IIS settings are allowing anonymous access and so your Identity object is null.
You should check for the inner exceptions behind the application crash but that will be your issue. You need to prevent anonymous access on IIS to get the Windows authentication passed through.
To manage IIS refer here https://stackoverflow.com/a/5458963/12285843

System.Security.Authentication.AuthenticationException: System error

I'm hosting an ASP.NET Core 3.1 web app with IIS 10, and it's throwing the following exception when trying to hit my API's through Postman:
System.Security.Authentication.AuthenticationException: System error.
at Microsoft.AspNetCore.Authorization.AuthorizationHandler`1.HandleAsync(AuthorizationHandlerContext context)
at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, Object resource)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
When using Postman on the machine running the web app, I can make successful HTTP requests and not have any issues. It seems to only be happening when trying to make external requests, but the error text is extremely unhelpful and I'm not sure where to begin diagnosing. As far as I can tell, the directory containing the web app project files doesn't have any specific security restrictions and the Application Pool is using an account with sufficient permissions to access and use them.
Has anyone seen error text like this before, or have any idea what the issue might be?
As it turns out, this exception was being thrown as a result of an incorrect database connection string. This particular request checks against a local database to ensure the user exists there.
Strangely enough, I've encountered this same type of issue before (where a database connection string is broken / changed at some point), but the resulting exception was much more specific in its Exception text and stack trace. The only thing I can't explain here is why the above error is so generic.

sharepoint object model in webservice

i am creating a webservice to provide one of the user poperty value to another application.
to do the same i am using sharepoint object model to connect to the mysite.
code : spsite site = new site(mysite url)
but i get the below error, kindly help.
error:
System.IO.FileNotFoundException: The Web application at "mysite url" could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
If this is a WCF service then by default there is no httpcontext, ergo, no spcontext. The fix is to enable "asp.net compatibility mode" in web.config. This is done with the following directive:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
I can think of two things that might be the cause of your problem:
-If your SharePoint is 64 bits, your application has to be built in 64 bit. The same applies for x86.
-The Target Framework option in your application needs to be set to 3.5
EDIT: I found an article about it. Maybe you could benefit from it.
http://blogs.technet.com/b/stefan_gossner/archive/2011/09/19/common-issue-new-spsite-returns-quot-the-web-application-at-http-server-port-could-not-be-found-quot.aspx

Access to operation of domain service is denied although user is authorized

A user of our system (Silverlight 4/WCF Ria Services) has a problem using Internet Explorer 9 and our application. Using FireFox isn´t a problem. I tried to reproduce the problem on other systems, with an equal configuration as the user´s system has, but i can´t reproduce the problem. So i think it´s a wrong configuration on the user´s system.
The problem is that the access to all domain service operations is denied, although the user logged in successfully to our application.
The server log contains for each operation that is called by the above user the following entry:
Exception of type System.UnauthorizedAccessException logged
Extended Properties: StackTrace - System.UnauthorizedAccessException:
Access to operation 'xxxx' was denied. at System.ServiceModel.DomainServices.Server.DomainService.ValidateMethodCall(DomainOperationEntry
domainOperationEntry, Object[] parameters, List`1 validationResults)
at System.ServiceModel.DomainServices.Server.DomainService.Query(QueryDescription
queryDescription, IEnumerable`1& validationErrors, Int32& totalCount)
Each DomainService class is decorated with the RequiresAuthentication-Attribute. No other attributes are applied on classes or methods. We are using a custom authentication service derived from AuthenticationBase and a custom user class derived from UserBase.
The user has the following programm versions:
IE9 Version: 9.0.8112.16421
Silverlight Version : 4.0.60531.0
Ok, i found the solution. The problem was that some Internet Options of the IE 9 in the Advanced Privacy Settings were set wrong.
The automatic cookie handling was overridden (CheckBox checked) and all cookies (First-party and Third-Party) were blocked. Also session cookies were denied.
After disabling the override of automatic cookie handling or allowing session cookies, the user can use our application as expected in the IE 9.

SerializationException on 'CustomIdentity' when user is denied in ASP.NET

I try to implement ASP.NET Authentication and Authorization on top of our existing database.
We have a website calling a webservice to fetch its data. To use the webservice, i need to provide the username and password.
Knowing that, I decided to implement IIdentity and IPrincipal to store the encrypted password and be able to provide it when performing webservice calls.
In the future, we might want to use more of the built-in security of asp.net, so I implement membership and role provider and override just what I need (ValidateUser and GetRoles)
Though, after validating the user thanks to the membership provider implementation I am still setting my own CustomIdentity to the Context.User to be able to retrieve its password when needed.
It's working perfectly as long as the user is allowed to visit the page. but when the user is denied, instead of throwing an AccessDeniedException, the framework throws a Serialization exception on my CustomIdentity.
I found a perfectly similar behaviour with more details described on this link , but no answer have been posted.
My exception is exactly the same as on the link above
Type is not resolved for member'CW.CustomAuthentication.CWIdentity,CW.CustomAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.Serialization.SerializationException: Type is not resolved for member 'CW.CustomAuthentication.CWIdentity,CW.CustomAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SerializationException: Type is not resolved for member 'CW.CustomAuthentication.CWIdentity,CW.CustomAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.]
Microsoft.VisualStudio.WebHost.Connection.get_RemoteIP() +0
Microsoft.VisualStudio.WebHost.Request.GetRemoteAddress() +65
System.Web.HttpRequest.get_UserHostAddress() +18
System.Web.HttpRequest.get_IsLocal() +13
System.Web.Configuration.CustomErrorsSection.CustomErrorsEnabled(HttpRequest request) +86
System.Web.HttpContext.get_IsCustomErrorEnabled() +42
System.Web.Configuration.UrlAuthFailedErrorFormatter.GetErrorText(HttpContext context) +16
System.Web.Security.UrlAuthorizationModule.WriteErrorMessage(HttpContext context) +29
System.Web.Security.UrlAuthorizationModule.OnEnter(Object source, EventArgs eventArgs) +8777783
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Is it correct to use membership and custom IIdentity and IPrincipal at the same time?
If not, where to add properties like the password or other userdata if I use the membership and role providers?
Best regards,
Stephane Erbrech
after some more testing, according to what the link I posted said, it seems that this error is happening only when I run in debug mode from visual studio. If I set the project to run in IIS, the error is gone and the security implementation works as expected.
---Is that a bug in the lightweight webserver implemented in Visual studio then?---
Edit :
You can go in the Properties of your web project, go to the "Web" tab, and check "Use local IIS Server". However, this will require you to run Visual Studio as an Administrator and to have IIS installed on your machine, so that VS can create the virtual directory in the local IIS server when it loads the project.
In my case, I simply had to inherit from MarshalByRefObject.
public class IcmtrIdentity : MarshalByRefObject, IIdentity
{
...
}
This might not be the correct answer, but I had this issue also but fixed it.
Originally, I just had a custom class that inherited GenericIdentity (or implimented IIdentity). When I finally created a custom class which inheritted GenericPrincipal (or implimented IPrincipal) then it all worked?
my CustomPrincipal class did nothing but inherited from GenericPrincipal and had one constructor which called the base constructor.
Both the CustomPrincipal and CustomIdentity classes did NOT impliment any Serialization or ISerializable stuff. Then again, my classes were all very basic.
You can go in the Properties of your web project, go to the "Web" tab, and check "Use local IIS Server". However, this will require you to run Visual Studio as an Administrator and to have IIS installed on your machine, so that VS can create the virtual directory in the local IIS server when it loads the project.
I had the same issue when trying to run the web app using CustomIdentity. In order to set the project to use your IIS in VS 2008, you will need to define the URL to your application pool in your web application project.
This can also be resolved by adding the assembly containing your custom identity to the GAC on your dev machine.