System.Security.Authentication.AuthenticationException: System error - asp.net-core

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.

Related

"Accessing expired session" exception from DistributedSession in ASP.Net Core

I have a .Net Core 3.1 web application and I keep getting "Accessing expired session" exception from "Microsoft.AspNetCore.Session.DistributedSession", which prevents my website from loading.
Steps to reproduce:
Successfully navigate to the website, which caches the session cookie with the browser
Restart web server, which clears the in-memory session cache
Refresh browser, which tries to re-use previously cached session cookie
At this point the exception just loads up my logs until the web server crashes. The only way to get it to stop is to clear the session cookie in the browser, which will allow it to generate a fresh session cookie.
Why does the session mechanism, which I enabled using AddDistributedMemoryCache and AddSession, not just create a fresh session when it gets this request using the old cookie? If I could catch the exception somewhere, maybe I could deal with it in my code, but I do not even know how to trap the exception. Can anyone offer a way to prevent this error without manually deleting the browser cookie?
Additional Info:
I found the source code for this, and apparently, it is not actually an error, but yet it is preventing my page from rendering and it is crashing my webserver with an out of memory exception because it logs the message 1000's of times. Any suggestions for how to get around this?
Source Code Logging
Source Code Handling Event
After months of digging into this issue, I finally discovered what is going on. I have written a custom ILoggerProvider so that I can control how things going through ILoggerFactory are getting logged. Inside my ILoggerProvider, my code references Session. Every time that Session is referenced, Microsoft's code writes another "Accessing expired session" message to the log, which triggers my code, which accesses Session, and so on, causing an infinite loop. Now, I just need to refactor my ILoggerProvider to be smart enough to avoid causing infinite loops.

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

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();

System.Net.WebException: The request failed with HTTP status 401: Unauthorized

Ok, so I have this .NET 1.1 application (written by someone way back) which is like a document repository and it worked fine in the past. I suddenly get this error when trying to search for items/documents:
Page: /CPDEPforIT/SearchResults.aspx
Error:
System.Net.WebException: The request failed with HTTP status 401:
Unauthorized. at
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream responseStream, Boolean
asyncCall) at
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodName, Object[] parameters) at
CPDEPforIT.InktomiSearchService.soapSearchService.getSearchResults(SearchInput
in0) at CPDEPforIT.SearchResults.GetDatasetForSearchQuery(SearchInput
searchInput) at CPDEPforIT.SearchResults.Page_Load(Object sender,
EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at
System.Web.UI.Control.LoadRecursive() at
System.Web.UI.Page.ProcessRequestMain()
I don't remember any changes. Could this have been caused by something external to the application (IIS configurations/permissions, Server, Database)?
There are several things you need to verify.
Does the web service you are trying to access allow Anonymous Access? Authentication can be tricky for web-to-web calls
What is the web application running under, IWAM_xxx or IUSR_xxx? Or are you using an application pool running under a specific identity?
You may want to make sure your web application server's ASPNET or NETWORK SERVICE accounts can access your web service server.
If you want to get it working you could just provide an account for Anonymous Access...
Thanks!
I have also faced this type of issue before. In my case permission to the code folder works. Please check the folder permissions and then try with the IIS permissions.

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.