Changing Report Viewer control credentials
If you have a Web Forms application containing a Report Viewer control, and you want to specify the credentials used to access your report server, you may have noticed that it is not as easy as you thought.
The property NetworkCredentials stores the user and password that we want use to execute the report but unfortunately it is read only and there is not a set method to change that value.
Does that mean we only can execute the report by using the credentials of the current Windows user? Don't panic, there is an alternative way to do it.
For this case, I have created a very simple application called MyReportViewerWebAPP containing a ReportViewer control. Here is the code:
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyReportViewerWebAPP{
publicpartialclass_Default : System.Web.UI.Page
{
protectedvoid Page_Init(object sender, EventArgs e)
{
ReportViewer1.ServerReport.ReportServerCredentials =
newMyReportServerCredentials();
}
}
[Serializable]
publicsealedclassMyReportServerCredentials :
IReportServerCredentials
{
publicWindowsIdentity ImpersonationUser
{
get
{
// Use the default Windows user. Credentials will be
// provided by the NetworkCredentials property.
returnnull;
}
}
publicICredentials NetworkCredentials
{
get
{
// User name
string userName = "MyUser";
// Password
string password = "MyPassword";
// Domain
string domain = "MyDomain";
returnnewNetworkCredential(userName, password, domain);
}
}
publicbool GetFormsCredentials(outCookie authCookie,
outstring userName, outstring password,
outstring authority)
{
authCookie = null;
userName = null;
password = null;
authority = null;
// Not using form credentials
returnfalse;
}
}
}
This is the easiest way, however, we can do a most sofisticated and secured code.
If we read the user information from the Web.config file instead of storing it, the credentials will not be stored in session, reducing the vulnerable surface area to the Web.config file, which can be secured with an ACL:
public ICredentials NetworkCredentials
{
get
{
// User name
string userName =
ConfigurationManager.AppSettings
["MyReportViewerUser"];
if (string.IsNullOrEmpty(userName))
thrownew Exception(
"Missing user name from web.config file");
// Password
string password =
ConfigurationManager.AppSettings
["MyReportViewerPassword"];
if (string.IsNullOrEmpty(password))
thrownew Exception(
"Missing password from web.config file");
// Domain
string domain =
ConfigurationManager.AppSettings
["MyReportViewerDomain"];
if (string.IsNullOrEmpty(domain))
thrownew Exception(
"Missing domain from web.config file");
returnnew NetworkCredential(userName, password, domain);
}
}