Authentication Issue when accesing Reporting Service - asp.net

Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
When the user clicks on the button to download the .pdf which the Reporting automatically generates (the end-user never sees the html version of the Report), it asks for windows credentials.
If the user enters a valid credential (and this credential must be a valid credential on the server which the Reporting Service is deployed), the .pdf is obviously downloaded.
But this can't happen. The end-user must download the .pdf directly, without asking for credentials. Afterall, he doesn't even have the credentials.
Response.Redirect("http://MyServer/ReportServer/Pages/ReportViewer.aspx?%2fReportLuiza%2fReportContract&rs:Format=PDF&NMB_CONTRACT=" + txtNmbContractReport.Text);
The code snippet above, shows the first version of my code when the user clicks the button. This one propmts for the Windows credentials.
I already tried to change on IIS the Authentication of the virtual directory ReportServer, but the only one which works is the Windows Credentials. The other ones doesn't even let me open the virtual directory of the Report or the Report Manager's virtual directory.
When I tried to change it to Anonymous Authentication he couldn't access the DataBase. Then I choose the option to Credentials stored securely on the report server. Still doesn't work.
The physical directory of my ReportServer virtual directory points to the reporting server folder on the Hard Disk (C:\Program Files\Microsoft SQL Server\MSSQL.5\Reporting Services\ReportServer). I moved the same folder to my wwwroot directory.
Didn't work. The virtual directory didn't even open. Then I read this could be a problem because I had the same name on two folders (one in C: and other in wwwroot). So I changed the name of the one in wwwroot. Same issue of the DataBase connection couldn't be done.
I returned the physical path to C:
Below, is the second version of my button's event code:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
When I'm debugging (on Visual Studio 2010), the code above works fine, doesn't asking for credentials (unfortunately, it doesn't prompt the option to open, save or cancel de file download. But this is another problem, no need to worry with it now) and save the file on C:.
When published, the code doesn't work. An erros says: The permission granted to user 'IIS APPPOOL\ASP.NET v4.0' are insuficient for performing this operation. So I added to the Reporting Service's users this user. When I tried again, the error is: Login failed for user IISAPPPOOL\ASP.NET v4.0. Cannot create a connection to data source 'MyDataSourceName'.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Summarizing: I need a solution where there is no credential prompt, and the user can choose where it wants to save the .pdf file.
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.

One solution would be to create a new App Pool with an account that has the rights to access your restricted resources and then assign your web application to it.

Related

Directory.CreateDirectory failed on Remote Server

I am working on a small project, in asp.net mvc3, that would copy the deployment files from a local drive to a share drive on a window server 2008 R2 server. I am connected using WMI, and the connection is successful. However, I tried to create a folder, and I receive the message "Logon failure: unknown user name or bad password." Here is a sample code:
bool isConnected = false;
options.Username = user.Name.Trim();
options.Password = user.password.Trim();
mScope = new ManagementScope("\\\\xxx.xxx.xxx.xxx\\root\\cimv2", options);
mScope.Connect();
if (mScope.IsConnected == true)
{
//I've gotten to this point. Then, the code below throw the exception
Directory.CreateDirectory(#"\\\\xxx.xxx.xxx.xxx\Tester\shareFile.txt");
isConnected = true;
}
I'd like to know what am I doing? Is that the right way of doing it?
it is the correct way however it will be the current user you are trying to access that gets passed to the remote computer to create the directory. The management scope at this point has nothing to do with Directory.CreateDirectory. These are 2 different "worlds". you do give the creds to ManagementScope but this has no affect on Directory.CreateDirectory. you could use impersonation to do what you are wanting to:
How do you do Impersonation in .NET?
it is unclear though if you are doing this in ASP.NET/MVC or a different platform. your tags indicate ASP.NET MVC but not your main question.
remember, if you are using ASP.NET/MVC, the credentials of the app pool are being used to perform such actions.

Reporting Services 2008 - 401: Unauthorized

I've an application that connects to Reporting Services in SQL Server 2008 R2.
The error is the following:
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 Microsoft.SqlServer.ReportingServices2005.Execution.ReportExecutionService.LoadReport
(String Report, String HistoryID)
The application is running in production fine in 2 different customers, so it's not a codeing issue.
I'm trying to install it now on a customer's server, which is using AD. The SQL Server and the IIS is all in the same machine though, so I don't really care about AD.
It runs if I run IE as Administrator, but it doesn't work with other users. The ASP.NET app is connecting to SSRS using a user created in the local machine (called ReportingServicesUser), member of the ReportingServicesUser group.
Things I've tried:
Adding ReportingServicesUser to the Site Settings in the RS website (did the same for Network Service, IUSR, the Authenticated Users group, Local Service, etc)
Adding ReportingServicesUser to the folder permissions in the RS website (did the same for Network Service, IUSR, the Authenticated Users group, Local Service, etc)
Added permissions for that users to the databases (app database and RS related dbs)
Added NTFS permissions to the RS folders (I will double check though).
Connecting to the RS using http://localhost, http://computername and http://domain.com
For reference, the code is this (simplified version):
var service = new ReportExecutionService();
service.Credentials = new NetworkCredential("ReportingServicesUser", "password");
service.Url = "http://computername:90/ReportServer/ReportExecution2005.asmx";
service.ExecutionHeaderValue = new ExecutionHeader();
var execInfo = new ExecutionInfo();
execInfo = service.LoadReport("path-to-the-report", null);
===> Here it throws the exception
I've read a lot of posts and pages about this but I cannot get an answer that works for me.
OK, I've finally had to change the code to:
rs.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
and it worked. Probably there's another solution but I couldn't find it out.
Are you sure you gave "ReportingServicesUser" browse permissions for the specific report in ssrs? The request never made it to the server it seems but I would check \Reporting Services\LogFiles just to be certain.
Also, Your "report user" user needs to be defined on the reporting server with the credentials you send.

Active directory - exception has been thrown by the target of an invocation

I have a web application in a separate server than Active Directory and I want to change a user password. The code is the next:
string newPassword = Membership.GeneratePassword(int.Parse(WebConfigurationManager.AppSettings["passLenght"]),
int.Parse(WebConfigurationManager.AppSettings["passNonAlpha"]));
DirectoryEntry de = new DirectoryEntry(WebConfigurationManager.ConnectionStrings["ADConnString"].ConnectionString,
WebConfigurationManager.AppSettings["ADAdmin"], WebConfigurationManager.AppSettings["ADAdminPass"]);
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(objectClass=user) (userPrincipalName=" + name + "))";
SearchResultCollection results = deSearch.FindAll();
if (results.Count == 1)
{
foreach (SearchResult OneSearchResult in results)
{
DirectoryEntry AlterUser = OneSearchResult.GetDirectoryEntry();
AlterUser.AuthenticationType = AuthenticationTypes.Secure;
AlterUser.Invoke("SetPassword", newPassword);
AlterUser.CommitChanges();
AlterUser.Close();
}
}
When I run this in my development environment (where Active Directory and the web application are on the same server) it is working. But when I try to run it in the production environment I am having the next error:
Exception has been thrown by the target of an invocation
What am I missing?
Thanks.
EDIT:
I could go deep in the exception error and I get this:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Permissions are the issue. The account under which your ASP.NET code is running doesn't have the permission to set the account password.
Either:
Run the AppPool under a user that has the required permissions, or
Use impersonation to elevate the permissions for the SetPassword call
The reason it is working in your dev environment/failing in production is likely due to a combination of:
You are running the app under the Visual Studio development web server that runs under your user account, which has the necessary permissions. Running it under "real" IIS will run it under a less privileged account.
In the live environment there's another machine hop from the web server to the AD server, and the credentials don't get passed along. The web server needs to have network credentials (either as part of the AppPool identity, or a call to LogonUser) in order to authenticate to AD.
The code looks correct. This could be happening because the password your sending though Active Directory does not meet the minimum requirements. Trying using a more complex password such as "M2k3ThisWork!"
If you want to change the password of AD then you use this
AlterUser.Invoke("ChangePassword", OldPassword, newPassword);

How do I access database via virtual folder which points at a remote share

I'm having a problem getting access to a database which lives on a remote server.
I have a ASP.NET 2.0 webpage that is trying to connect to a database.
The database is accessed via a virtual folder (which I set up in IIS).
The virtual folder points at a remote share which contains the database.
The virtual folder (in the web apps root directory) is pointing at a share on a remote server via a UNC path:
\\databaseServerName\databaseFolder$\
The virtual folder has 'read' and 'browse' permissions set to 'true'.
I store the connection string in the 'appSettings' section of the web.config:
<add key="conStrVirtual" value="Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://webAppServerName/virtualFolderName/databaseName.MDB;Jet OLEDB:Database Password=dumbPassword;"/>
The connection object is declard on my .aspx page:
Dim objConnVirtual As New OleDbConnection(ConfigurationManager.AppSettings("conStrVirtual"))
Here is the code that tries to use the connection object:
Public Sub Test()
If objConnVirtual.State <> ConnectionState.Open Then
objConnVirtual.Open()
End If
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM TableName", objConnVirtual)
objDR = cmd.ExecuteReader()
If objDR.Read() Then
response.write("Shazaam! Data shows up here")
End If
objDR.Close()
objConnVirtual.Close()
End Sub
When I run the above code I get the following error (on this line of the code 'objConnVirtual.Open()':
Exception Details: System.Data.OleDb.OleDbException: Not a valid file name.
I have checked the database name and it is correct (even copy/pasted it to make sure)
If I put the 'Data Source' section of the connection string into the address bar of my browser I can successfully see the contents of the share on the remote server.
Not sure if this is a problem with permissions or with the code.
I have googled the crap out of this but have not been able to find a solution.
Any help is much appreciated.
When accessing a remote Access MDB database, you have to specify a UNC path like \\remoteMachine\Share\test.mdb.
Make sure your application pool identity has the right permissions to connect to the remote share. By default on IIS 6 you are working with the Network Service account, which is by default not allowed to access a remote share.
The best way is to let the AppPool run with a dedicated service user.
What is the account being used on your server when your web app tries to read the db file? Whatever this user account is, it needs to have permissions to read that folder/file. In IIS6 you can configure the virtual folder to use any user account... on the Directory Security tab there's an Edit button under Authentication and access control.
It seems likely that your error message is just a generic error message, and the permissions problem is your real issue.
make sure the two servers have internal access to each other and also specify the ip & port of db server in your connection string .
Update
I should also mention that it works on my machine (but not once loaded up to the production box) if I declare the connection string in the 'appSettings' section of the web.config like this:
<add key="conStrVirtual" value="Provider=Microsoft.Jet.OleDb.4.0;Data Source=\\databaseServerName\databaseFolder$\databaseName.MDB;Jet OLEDB:Database Password=dumbPassword;"/>
This leads me to think that it could be an issue with needing to use domain credentials other than the local IUSER account.
UPDATE
First up, thank you to everyone who submitted answers.
However, we ended up not using the 'connect to remote database via virtual folder' method because the complexity of the permissions needed to get this to work was causing us more problems than it was worth. We put the UNC path back into the connection string, which may not be the best way to do this, but is working for us.

ASP.NET: System.UnauthorizedAccessException - Access to Path Denied

I have an ASP.NET web application which does the following:
Reads an Excel file.
The excel file will have an image URL located in it that points to somewhere on the internet.
The program reads each image URL and store it into a temporary folder in the web server.
The application then resizes (changes the width and height) of the image.
Finally, the application will save that image to another folder.
I am getting the following exception:
System.Net.WebException: An exception
occurred during a WebClient request.
---> System.UnauthorizedAccessException:
Access to the path
'\abcserver\target03\3111\35644\www.testing.com\web\content\images\TempStorage\tempImage.jpg'
is denied. at
System.IO.__Error.WinIOError(Int32
errorCode, String maybeFullPath) at
System.IO.FileStream.Init(String path,
FileMode mode, FileAccess access,
Int32 rights, Boolean useRights,
FileShare share, Int32 bufferSize,
FileOptions options,
SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy) at
System.IO.FileStream..ctor(String
path, FileMode mode, FileAccess
access) at
System.Net.WebClient.DownloadFile(Uri
address, String fileName) --- End
of inner exception stack trace ---
at ProcessImage.GetFileFromUrl(String
imageFileUrl, String newFileName)
at
uploadexceldata.UploadExcelData(String
fileName)
foreach (DataRow dr in dt.Rows) // Reading each excel row
{
if (dr[0].ToString() != "")
{
id= "";
path = "";
manuId = "";
id= dr[0].ToString();
path = dr[1].ToString();
fileNameOnly = iProImg.GetFileNameOnly(path);
objDb.openConnection();
strSqlGroupInfo = "select ManufacturerID from manufacturers where id='" + id+ "'";
dTblManu = objDb.BuildDT(strSqlGroupInfo); // To Fill data to Datatable
objDb.closeConnection();
if (dTblManu.Rows.Count > 0)
{
manuId = dTblManu.Rows[0][0].ToString();
}
if (manuId != "")
{
tempUploadPath = "images/TempStorage/";
tempUploadPath = Server.MapPath(tempUploadPath);
if (!Directory.Exists(tempUploadPath))
{
Directory.CreateDirectory(tempUploadPath);
}
tempFilePath = tempUploadPath + "\\tempImage.jpg";
tempFilePath = tempFilePath.Replace("/", "\\");
previewPath = Server.MapPath("images/previews/" + manuId);
thumbNailPath = Server.MapPath("images/thumbnails/" + manuId);
if (!Directory.Exists(previewPath))
{
Directory.CreateDirectory(previewPath);
}
if (!Directory.Exists(thumbNailPath))
{
Directory.CreateDirectory(thumbNailPath);
}
fileNameOnly = "\\preview" + id+ ".jpg";
fileNameOnly = fileNameOnly.Replace("/", "\\");
previewPath = previewPath + fileNameOnly;
tempPartialPathP = "images\\previews\\" + manuId + fileNameOnly;
fileNameOnly = "\\thumbnail" + id+ ".jpg";
thumbNailPath = thumbNailPath + fileNameOnly;
tempPartialPathT = "images\\thumbnails\\" + manuId + fileNameOnly;
try
{
iProImg.GetFileFromUrl(path, tempFilePath);
rowCounter++;
iProImg.ReSizeImage(tempFilePath, previewPath, previewSize);
iProImg.ReSizeImage(previewPath, thumbNailPath, thumbNailSize);
}
catch (Exception ec)
{
errorRowCount++;
iLog.LogErrorToFile("uploadExcel", ec.ToString(), "path : " + path + ",tempFilePath :" + tempFilePath);
}
finally
{
if(File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
}
} // If manuid!=""
} //if (dr[0].ToString() != "")
Does anyone have any suggestions on how to fix this exception?
Try setting the access permissions to "Full control" for the .Net user from where you are reading/saving the files.
No answers in the world solved this for me until I stumbled on the answer for myself:
UN-ENCRYPT THE FILE
You can grant full permissions to everyone on your entire hard drive, it still won't allow ASP.NET decrypt files.
If you are certain the file isn't encrypted, then you just need to add the ASPNET account to the file or folder you want to access. But make sure its not encrypted first!
In reply to what was said : "This is a remote server and the folder has full read/write permission granted.Still not working "
Make sure the .Net user / machine account user has full permissions for that Folder.
Also, add < identity /> to your config file
Make sure the ASP.NET account has read/write permission on the folder you're writing to (basic windows security).
How to:
http://www.microsoft.com/windowsxp/using/networking/security/permissions.mspx
(first 4 steps, check the boxes and click OK)
[EDIT]
You need to authenticate yourself with an account known on the remote server. You probably gave rights to the local ASP.NET account on the remote server, which won't work because that's not the user you access the folder with (from the webserver).
[/EDIT]
All of the above, plus you may need to add this tag:
<identity impersonate="true" userName="accountname" password="password" />
Read this KB article and if you are going from browser to iis to a file share, that counts as two hops and now you need to configure Kerberos Delegation. System administrators much smarter than me have tried to configure kerberos delegation and failed. Move your images or you IIS instance so that they are on the same machine.
First, narrow down your problem by temporarily granting Everyone full permission on that particular path. If it works, then you know for a fact it's a simple permission issue and you just need to figure out which acct needs proper permission. Probably the Anonymous User account (double check this setting in IIS Admin) and not the ASP.NET account. (don't forget to pull permission for Everyone)
If you need to, I believe you can use FileMon to see which account is attempting to access a particular file. Could be wrong, I haven't used this tool in a while.
One last thing... is the read-only flag set on the file? :)
I had the exact same problem today. After spending hours trying to track down what was causing the issue I found out that the permissions for the folder that was being written to were incorrect. Essentially, the folder was readonly from the perspective of the user being used to create the file.
Try doing the following for the folder in question:
Right Click on the folder and select properties
Click on the Sharing tab and then click on the Permissions button
Make sure to add whatever user is going to writing to the folder permissions to do so
Back at the properties page, click the Security tab
Make sure to add whatever user is going to write to the folder permissions to do so
Seeing as this question was asked 6 months ago, I'm assuming that you've already solved the issue...but I just thought I'd document my solution just in case it becomes useful to someone else in the future as they try to figure out how to solve this UnauthorizedAccessException.
Check that the image file (jpg) you're writing to the tempStorage has the proper permissions for the webuser account(aspnet or iis_wpg). You can set the TempStorage directory to replace permisson entries on all child objects.
Right Click TempStorage folder and select properties
Select the security tab (ensure the proper read/write/modify permissons are here)
Click the Advanced button
Check the second checkbox - Replace permissions entries on all child objects with entries shown here that apply to child objects.
Now all files that you add to the TempStoreage folder will inherit the permissions allowing you webuser account to read the jpg file.
Instead of granting permissions to ASPNET user, grant permissions to NETWORK SERVICE user. Modify permissions within the folder should be enough, no need to give full permissions (no reason to give more permissions than needed)
for more details read forum : http://forums.asp.net/t/1013434.aspx/1
the error is pretty obvious there Access to the path 'bin\myprojname.pdb\' is denied. the user the web console process is running under (not the user you created in the webconsole, the actual windows user), most likely "Network Service" doesnt have permissions to that folder.
You can either - Right click on that folder, goto permissions and add the "Network Service" user - Right click on that folder, goto permissions and add the "Everyone" user
that should fix that problem.

Resources