SSRS Showing Authentication Error - asp.net

I am running a Reports Server (SSRS) and I am calling the reports from within my ASP application. Whenever I try to load a report through the site itself it shows me a HTTP 401 Error, both locally and accessing through the domain. If I open the reports in the ReportServer itself I can open them up fine, the problem is loading through the web page. I tried changing the credentials in the data source itself but everything was fine, switched the SQL User credential and Windows Authentication and nothing helped. Any help would be appreciated as I am at a loss about what to do.
This is the local server error:
[WebException: The request failed with HTTP status 401: Unauthorized.]
Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.GetSecureMethods() +232
Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.IsSecureMethod(String methodname) +60
Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.SetConnectionSSLForMethod(String methodname) +16
Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.ProxyMethodInvocation.Execute(RSExecutionConnection connection, ProxyMethod`1 initialMethod, ProxyMethod`1 retryMethod) +831
Microsoft.Reporting.WebForms.SoapReportExecutionService.LoadReport(String report, String historyId) +34
Microsoft.Reporting.WebForms.ServerReport.EnsureExecutionSession() +175
Microsoft.Reporting.WebForms.ServerReport.SetParameters(IEnumerable`1 parameters) +162
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
ASPX Codebehind:
ReportViewer1.ServerReport.ReportServerUrl = new System.Uri("serveradress");
ReportViewer1.ServerReport.ReportPath = "/TrialBalance";
Microsoft.Reporting.WebForms.ReportParameter[] Param = new Microsoft.Reporting.WebForms.ReportParameter[1];
Param[0] = new Microsoft.Reporting.WebForms.ReportParameter("ID", Convert.ToString(Session["BranchID"]));
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.ServerReport.SetParameters(Param);
ReportViewer1.ServerReport.Refresh();
Attempts!
1) Gave AppPool LocalSystem permissions
2) i can access the Reportserver using domain.com/ReportServer or localhost/ReportServer, problem only occurs within the ASP app.
3) Verified SSRS Service Account permissions.
4) DataSource connects without issue.
5) The reports were working without issue a week ago, I migrated a server image to another more powerful server and I believe this is were it got broken but I don't see how as the image is the SAME. Nothing changed.
6) I can call the ReportServer (Report Loads and all) in my local development computer, which aims at the remote server. If I access the same ASPX in the website it gives me the HTTP 401 error
7) Changed in programing to aim at localhost directly... this was the error:
An error has occurred during report processing. (rsProcessingAborted)
Cannot create a connection to data source 'DataSource1'. (rsErrorOpeningConnection)
Cannot open database "CoopBranches" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\SYSTEM'.
Which is weird because I am testing the data source and it is connecting without any issue.

I came across with the same issue several days ago and here are some suggestions based on what I did on mine.
On you app pool try to indicate/impersonate a domain user then give that report permissions on the server.
This one gives a big difference. Try to see what ReportViewer1 is resolving to, what I notice is that if your application goes to
http://{YourReportServerURL}/ReportServer/Pages/ReportViewer.aspx?/{YourReportName}&{Param1}={ParamValue}
Then you will have a multi hop authentication issue beacuse that URL Redirects to another URL that eventually resolves to, loosing the authenticated user in the process when not using Kerberos
http://{YourReportServerURL}/ReportServer?/{YourReportFolder}/{YourReportName}&{Param1}={ParamValue}
If thats the case try to generate the URL manually like such
http://{YourReportServerURL}/ReportServer?/{YourReportFolder}/{YourReportName}&{Param1}={ParamValue}

Related

How can I setup my ASP.NET backend in IIS?

I am building a website that is managed over Microsoft IIS. I want my whole website to work like this:
The IIS gets a HTTP request over port 80 for the main website and then answers with the HTML and JS documents. These documents remain static and are simply saved as files on the server, which the IIS reads and send to the client without further modifying it.
In the JS document that the client gets, there are fetch()-commands that send additional requests during runtime over a different port when the user is interacting with the website. The browser should get back JSON data from the server. I have written a ASP.NET web application to do this.
This is what my current setup in IIS looks like:
enter image description here
I have set up a site for step one (front-end) and one for step two (back-end). I added a binding for the first site to port 80 and set the default document. I linked the second site to the directory in which the build binary of my ASP.NET application lies. Then, I added the binding with Port 5000 and the same IP-Address to the second site.
Step one works. When sending a request over Port 80, I get the website documents. But the second step doesn't. In debugging mode of Visual Studio, it works fine and it does it job. But I didn't manage to get step two working in IIS yet. The response I get when sending my requests is a 404. I created an additioonal controller to my back-end for testing that should just respond some hardcoded strings and do nothing more. Actually that works. I do get a 200 and the strings as a response. So there must be something wrong with the ASP.NET back-end communicating with my database.
I found out that everytime, when sending my request, an error log is written by my back-end. It says:
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware1
An unhandled exception has occurred while executing the request.
System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32 maxDepth)
at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|27_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
Again, I do not get the error when debugging the back-end ap
Can someone help?
The problem was basically wrong SQL Server permission setup. I managed to solve my problem. This may be helpful to people who are facing similar problems:
The "JsonException object cycle" error itself was not that helpful at all. So, I went into further debugging. I attached VisualStudio Debugging to the actual running IIS process like so: https://learn.microsoft.com/en-us/visualstudio/debugger/attach-to-running-processes-with-the-visual-studio-debugger?view=vs-2019
This was helpful for finding the reason for the error, as I could now experience log messages that were much more fitting to the actual error. Mind that you have to change the hostingModel to "outofprocess" in the web.config in order to attach to the standalone .Net process. https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/out-of-process-hosting?view=aspnetcore-5.0
In case you are using SQL Server Management Studio, create a login for "NT Authority" (Object Explorer > Security > Logins > NT-Authority), grant access to your database and make sure that you do not select a "deny" role in user mapping, because I did so, and that was causing my error.

Access denied error when my Azure Website is shutting down (removing cache items)

My app is working well on Azure Websites (not Web role, please exclude web role specific answers !), but sometimes I got the following error in my logs :
System.UnauthorizedAccessException: Access to the path 'C:\DWASFiles\Sites\myAzureWebSiteNameHere\VirtualDirectory0\site\wwwroot' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator`1.CommonInit()
at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
at System.IO.Directory.EnumerateFiles(String path)
at System.Web.WebPages.Deployment.WebPagesDeployment.AppRootContainsWebPagesFile(String path)
at System.Web.WebPages.Deployment.PreApplicationStartCode.OnChanged(String key, Object value, CacheItemRemovedReason reason)
at System.Web.Caching.CacheEntry.CallCacheItemRemovedCallback(CacheItemRemovedCallback callback, CacheItemRemovedReason reason)
This happened just before the site is restarted (by Azure, not by me, probably for a maintenance operation on the VM containing the site). So I concluded that it happened during a "shutting down" operation, when the system try to clear the cache.
I'm using the Asp.net cache like this : HttpContext.Current.Cache[myKey] = something and I have not define any specific callback like CacheItemRemovedCallback. The above callstack confirms the error is on a system callback.
It seems to be Azure specific (and perhaps even specific to Azure Websites), because the same website on an on-premise server never had this kind of error.
Do you know how to prevent this error from happening ? Thanks !

Windows Azure - NetworkInformationException (0x80004005): Access is denied - HttpWebRequest

GetResponse works fine on my local machine but when deployed to Windows Azure I receive the following exception. My ASP.NET website runs an exe I created as a new process and it is the code in the exe that encounters the exception listed below. Can anyone suggest possible permission settings I can look at to solve this problem?
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.UserAgent = _userAgent;
request.Timeout = 50000;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.Net.NetworkInformation.NetworkInformationException (0x80004005): Access is denied
at System.Net.NetworkInformation.SystemIPGlobalProperties.GetFixedInfo()
at System.Net.NetworkInformation.SystemIPGlobalProperties.get_FixedInfo()
at System.Net.NetworkInformation.SystemIPGlobalProperties.get_HostName()
at System.Net.NclUtilities.GuessWhetherHostIsLoopback(String host)
at System.Net.ServicePoint.get_ConnectionLimit()
at System.Net.ConnectionGroup..ctor(ServicePoint servicePoint, String connName)
at System.Net.ServicePoint.SubmitRequest(HttpWebRequest request, String connName)
at System.Net.HttpWebRequest.SubmitRequest(ServicePoint servicePoint)
at System.Net.HttpWebRequest.GetResponse()
Need more information, but my first thought is that you are:
Trying to bind a socket to a privileged port (port <= 1024)
Trying to bind a socket to an IP you don't have on that machine
The user your local website runs that code has higher permissions of some kind than the user Windows Azure (eg the IIS AppPool?) runs it as
DirectoryService COM can not create an authentication object.
Review
http://blogs.msdn.com/b/distributedservices/archive/2009/11/06/a-com-server-application-may-stop-working-on-windows-server-2008.aspx
Try to launch the process from asp.net with specific credential.. i.e. using local user credential. It might be possible that azure is blocking unauthenticated process to access internet.

Searching Active Directory from ASP.NET

I have an asp.net website which searches Active Directory for user details using this code:
public static SearchResult GetUserProfileFromAD(string username)
{
DirectorySearcher searcher = new DirectorySearcher("(&(objectCategory=person)(sAMAccountName=" + username + "))");
return searcher.FindOne();
}
the website is working great on windows server 2003 and IIS5.
recently i move the website to a new windows server 2008 with IIS7.5
i Added application to iis and conect the website and i get this error:
The (&(objectCategory=person)(sAMAccountName=)) search filter is
invalid. 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.ArgumentException: The
(&(objectCategory=person)(sAMAccountName=)) search filter is invalid.
when i run my website through Visual Studio it works. the problem is only from IIS.
Can someone help me?
Your "username" variable is blank, causing your filter to terminate in a equal sign (which is, in fact. invalid) Without knowing more about your setup, it's hard to say. But it sounds distinctly like you don't have the authentication set up correctly for the website on your new server - causing whatever routine you have to fill in the username to not get anything back.
The error is clearly because "username" is an empty string. This is most likely because you're users are logging into your web-site anonymously. Please ensure that anonymous access is disabled in IIS.
However, it would be helpful if you can show the code which calls GetUserProfileFromAD.
Seems to me that the variable username is not being populated, if you say that you moved it to IIS try to check again for the security options, probable Windows Authentication is not configured yet.

log4net permission issue to write to application event log when the user is not in admin group in Windows 2008 R2 and IIS 7

I am having log4net permission issue from ASP.Net 4.0 web application to write to application event log, when the user is not in administrator group in Windows 2008 R2 and IIS 7. We are using NT authentication and impersonation. Once I assign the user to admin group it works fine.
I tried with many permission settings like giving Authenticated Users full permission to Eventlog in registry etc. and none of them work. If any one can help that will be great.
When I had a similar issue with logging to eventlog from a .net 1.1 app on Windows 2003 server I did CustomSD entry as below link and it worked
http://mossipqueen.wordpress.com/2008/08/04/cannot-open-log-for-source-you-may-not-have-write-access/
The error I get is below from log4net internal log.
log4net:ERROR [EventLogAppender] Unable to write to event log [Application] using source [*******]
System.InvalidOperationException: Cannot open log for source '*******'. You may not have write access. ---> System.ComponentModel.Win32Exception: Access is denied
--- End of inner exception stack trace ---
at System.Diagnostics.EventLogInternal.OpenForWrite(String currentMachineName)
at System.Diagnostics.EventLogInternal.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName)
at System.Diagnostics.EventLogInternal.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
at System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
at log4net.Appender.EventLogAppender.Append(LoggingEvent loggingEvent)
Maybe I'm missing something here but it looks like a simple permissions issue for that user. By default they don't have access to write to the application log file. I know you played around with the permissions but I'm not sure exactly what permissions you assigned.
Here is a Microsoft article on doing exactly what you want to do to overcome the error you are seeing:
http://support.microsoft.com/kb/2028427
If you follow this, you should solve your issue. I hope this helps.

Resources