Server Error in /MyApp Application (Access Denied)? - sql

I've just published my LS app to my host (WinHost) and I used the publish settings provided by my host and setup the database, etc. And when I go to my website address (where the app is located), I get the following page:
Server Error in '/MyAPP' Application.
Security Exception Description: The application attempted to
perform an operation not allowed by the security policy. To grant
this application the required permission please contact your system
administrator or change the application's trust level in the
configuration file.
Exception Details: System.Security.SecurityException: Request for the
permission of type 'System.Security.Permissions.SecurityPermission,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' failed.
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:
[SecurityException: Request for the permission of type
'System.Security.Permissions.SecurityPermission, mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
failed.]
Microsoft.LightSwitch.BaseServices.Logging.Utilities.HostEnvironment.RunningInAzureCore()
+0 Microsoft.LightSwitch.BaseServices.Logging.Utilities.HostEnvironment.RunningInAzure()
+108 Microsoft.LightSwitch.BaseServices.Logging.Utilities.HostEnvironment.get_IsEncryptionRequired()
+24 Microsoft.LightSwitch.WebHost.Implementation.LightSwitchHttpModule.Init(HttpApplication
application) +21
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +418
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +296
-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.18045
Now, I have made sure that my server is using .NET 4. I have checked that the credentials are correct, many times. The app debugs fine. Just not after I've uploaded it.
What gives? I understand that it says "SecurityException and Access Denied, etc" - but what the hell does that actually mean when everything i've entered is OK?

You may want to check the Application on the web server. Make sure that the application pool and application are running under the correct permission levels for the type of application.
It can be a bit tricky, but typically you will get an error inside the application if there are bad credentials to the database or authentication of the user. If the application itself fails, there may be a permissions issue inside IIS.

Check the trust level for your application. Go to your application, and click on the .NET trust level, and change it to FULL

Related

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.

Server Error in '/' Application. The requested operation cannot be completed. The computer must be trusted for delegation

I am trying to access my application deployed in IIS8. after successful authentication i am ending up with following error.
Server Error in '/' Application.
The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.
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.Security.Cryptography.CryptographicException: The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.
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:
[CryptographicException: The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.
]
System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope) +504
System.IdentityModel.ProtectedDataCookieTransform.Encode(Byte[] value) +89
[InvalidOperationException: ID1074: A CryptographicException occurred when attempting to encrypt 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.Encode(Byte[] value) +1082947
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +95
System.IdentityModel.Tokens.SessionSecurityTokenHandler.WriteToken(XmlWriter writer, SecurityToken token) +809
System.IdentityModel.Tokens.SessionSecurityTokenHandler.WriteToken(SessionSecurityToken sessionToken) +109
System.IdentityModel.Services.SessionAuthenticationModule.WriteSessionTokenToCookie(SessionSecurityToken sessionToken) +206
System.IdentityModel.Services.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequestBase request) +1124
System.IdentityModel.Services.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args) +103571
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
Have a look at https://github.com/brockallen/BrockAllen.MembershipReboot/issues/106
This solved the issue for us :
http://brockallen.com/2013/02/18/configuring-machine-key-protection-of-session-tokens-in-wif-and-thinktecture-identitymodel/

Failure writing to log file with RavenDB Embedded on Windows Azure

I am running an MVC web site on Windows Azure and using RavenDB embedded. If the web site is "cold" (unloaded from the Azure instance), I get the following error message on the first hit to the web site:
Server Error in '/' Application.
Failure writing to log file
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:
Microsoft.Isam.Esent.Interop.EsentLogWriteFailException: Failure
writing to log file
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:
[EsentLogWriteFailException: Failure writing to log file]
Microsoft.Isam.Esent.Interop.Api.Check(Int32 err) +21
Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance) +23
Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator
uuidGenerator, OrderedPartCollection`1 documentCodecs) +309
[InvalidOperationException: Could not open transactional storage:
C:\DWASFiles\Sites\reflix\VirtualDirectory0\site\wwwroot\App_Data\Data]
Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator
uuidGenerator, OrderedPartCollection`1 documentCodecs) +443
Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration
configuration) +994
Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
+313 Raven.Client.Document.DocumentStore.Initialize() +463 Reflix.MvcApplication.InitializeRavenDB(String dataDirectory, Boolean
rethrowException) +135 Reflix.MvcApplication.Application_Start()
+131
[HttpException (0x80004005): Could not open transactional storage:
C:\DWASFiles\Sites\reflix\VirtualDirectory0\site\wwwroot\App_Data\Data]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
context, HttpApplication app) +9859441
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +296
[HttpException (0x80004005): Could not open transactional storage:
C:\DWASFiles\Sites\reflix\VirtualDirectory0\site\wwwroot\App_Data\Data]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873784
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +254
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.18033
If I wait a minute or two, the web site comes up fine. So clearly this is a first-start issue. Anyone have any ideas how to resolve the problem?
My configuration:
MVC 4
.NET 4.5
RavenDB 2.0.2360
Update: The Azure team is looking at this as a possible defect with the Azure Websites. More updates as soon as I hear anything.
This was confirmed as a bug in Azure Websites, which has now been rolled out. I don't have any additional details, but the site now works (8/30/2013) and I have made no structural changes to the code.
Look at the event log, it will give you more info.
It looks like something is prevent proper write to the logs, check permissions, in particular, you may have CREATE_FILE permission, but not WRITE permission

WCF Service Exception

I'm currently working on an Silverlight 3 project, I'm using 2 machines to test it.
"harbinger" is the web server running Win7 + IIS . I've deployed the webpage and the WCF webservice to that machine.
I've entered the following url's in my browser :
http://harbinger:43011/UserService.svc
http://harbinger:43011/UserService.svc?wsdl
and got pages load expected contents for both
Next I've decided to check if I can call the webservice from my machine, I've added the ServiceReference, executed a call to one of the methods and .... BOOM :
System.ServiceModel.CommunicationException was unhandled by user code
Message="An error occurred while trying to make a request to URI 'http://harbinger:43011/UserService.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details."
StackTrace:
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at Energy.USR.UserServiceClient.UserServiceClientChannel.EndGetAllUsers(IAsyncResult result)
at Energy.USR.UserServiceClient.Energy.USR.UserService.EndGetAllUsers(IAsyncResult result)
at Energy.USR.UserServiceClient.OnEndGetAllUsers(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
InnerException: System.Security.SecurityException
Message=""
StackTrace:
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
InnerException: System.Security.SecurityException
Message="Security error."
StackTrace:
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
InnerException:
Can someone explain what just happened? What do I need to do to avoid this?
See this blog post - I think that's the root cause of your problem:
Enabling cross-domain calls for Silverlight apps on self-hosted web services
or this one here:
WCF and Silverlight with cross-domain issue
Without any special policy files, you won't be able to call cross-domain in Silverlight.

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.