Welcome to MSDN Blogs Sign in | Join | Help

Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

I've been playing around with using different forms of authentication / impersonation with the Report Viewer controls, and I thought I'd post the fruits of my efforts. Here we go:

Using Forms Authentication with the Winform Report Viewer control is easy -- Just pass in the creds and you're all done:

reportViewer1.ServerReport.ReportServerCredentials.SetFormsCredentials(null, "userName", "password", "domainName");
this.reportViewer1.RefreshReport();

Doing the same thing with the Webform Report Viewer control is kind of a pain in the tail. You actually have to implement an interface called IReportServerCredentials and write/borrow another subclass that handles all the cookie related stuff when dealing with Forms Auth.

I took most of the following code from the following help topic, btw:

http://msdn2.microsoft.com/en-us/library/microsoft.reporting.webforms.ireportservercredentials.aspx
 
Anyway, first create the code for your Forms Auth Login page:

         MyReportingService svc = new MyReportingService();
         svc.Url = "
http://myServer/reportserver/reportexecution2005.asmx";
         try
         {
            svc.LogonUser("myUserName", "MyPassword", null);
            Cookie myAuthCookie = svc.AuthCookie;
            if (myAuthCookie == null)
            {
               Message.Text = "Logon failed";
            }
            else
            {
               HttpCookie cookie = new HttpCookie(myAuthCookie.Name, myAuthCookie.Value);
               Response.Cookies.Add(cookie);
               string returnUrl = Request.QueryString["ReturnUrl"];
               if (returnUrl == null || !returnUrl.StartsWith("/"))
                  Message.Text = "Return url is missing or invalid!";
               else
                  Response.Redirect("
http://myServer/appFolder/default.aspx");
            }
         }
         catch (Exception ex)
         {
            Message.Text = "Logon failed: " + ex.Message;
         }

    

The code above calls LogonUser() against the SSRS web service so that we can get the Forms Auth cookie back from SSRS itself. Then, we stick the cookie into Response.Cookies, and forward the user to a page which has a ReportViewer control on it (in this case, http://myServer/appFolder/default.aspx)

OK, so now we're sitting on the page which has the Report Viewer control itself.

In Page_Load, we first see if the previous cookie exists...if it doesn't, we send you right back to the logon form:


        HttpCookie cookie = Request.Cookies["sqlAuthCookie"];
        if (cookie == null)
        {
            Response.Redirect("/appFolder/logon.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl));

        }    
      else
        {

            ReportViewer1.ProcessingMode = ProcessingMode.Remote;
            ReportViewer1.ServerReport.ReportServerUrl = new Uri("
http://myServer/reportserver");
            ReportViewer1.ServerReport.ReportPath = "/Report Project2/Report1";

            Cookie authCookie = new Cookie(cookie.Name, cookie.Value);
            authCookie.Domain = "myServer";
            ReportViewer1.ServerReport.ReportServerCredentials =
            new MyReportServerCredentials(authCookie);
         }

If the cookie IS there, we set a few properties on the Report Viewer control, then set the ReportServerCredentials property of the control equal to our authCookie. Here is where the implementation of IReportServerCredentials and that other "cookie-handling class" come in.

First, here's the implementation of IReportServerCredentials. It allows us to create a MyReportServerCredentials object:

class MyReportServerCredentials : IReportServerCredentials
{
    private Cookie m_authCookie;

    public MyReportServerCredentials(Cookie authCookie)
    {
        m_authCookie = authCookie;
    }

    public WindowsIdentity ImpersonationUser
    {
        get
        {
            return null;  // Use default identity.
        }
    }

    public ICredentials NetworkCredentials
    {
        get
        {
            return null;  // Not using NetworkCredentials to authenticate.
        }
    }

        public bool GetFormsCredentials(out Cookie authCookie,
            out string user, out string password, out string authority)
        {
            authCookie = m_authCookie;
            user = password = authority = null;
            return true;  // Use forms credentials to authenticate.
        }
    }

 
As I mentioned earlier, we also have to subclass the myServer.ReportExecutionService class and override a few methods in order to do the cookie-related work:

public class MyReportingService : myServer.ReportExecutionService
{
    private Cookie m_authCookie;

    public Cookie AuthCookie
    {
        get
        {
            return m_authCookie;
        }
    }

    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
        request.Credentials = base.Credentials;
        request.CookieContainer = new CookieContainer();
        if (m_authCookie != null)
            request.CookieContainer.Add(m_authCookie);
        return request;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        string cookieName = response.Headers["RSAuthenticationHeader"];
        if (cookieName != null)
        {
            HttpWebResponse webResponse = (HttpWebResponse)response;
            m_authCookie = webResponse.Cookies[cookieName];
        }
        return response;
    }
}

...and that's it. You may actually have better luck using the URL at the top of the page for your code copying and pasting as it contains HTML you can use for you logon page, too.

My biggest problem with this whole scenario was actually *finding* the help topic I needed...It would have nice if I could have searched on "forms authentication report viewer control" and been directed to the topic in question (grump, grump).

Published Friday, November 04, 2005 11:25 AM by russch

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Wednesday, November 30, 2005 12:25 PM by Dan
I did almost that exact search and it sent me here. Thanks for doing the legwork.

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, January 24, 2006 4:39 AM by William
Dear Russell,
I've tried the Forms Authentication with the Winform Report Viewer control but failed to display the report

i.e.
reportViewer1.ServerReport.ReportServerCredentials.SetFormsCredentials(null, "userName", "password", "domainName");
this.reportViewer1.RefreshReport();

and always return me rsLogonFailed.

However when I use the windows account "userName", "password", "domainName" in IE using http://XXX.XXX.XX.XX/reportServer, I can get the report.

Any comment? Thanks a lot.

Regards,
William

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Wednesday, April 12, 2006 2:47 AM by Karin
This is the closest I found to solving this issue. There is no equivalent in VB to the 'out' statement and I'm getting also sorts of grief with the interface.

Do you know or can you direct me to how this code might work in VB?
Cheers,
Karin

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Monday, April 17, 2006 5:20 PM by russch
I think ByRef is the closest you can get to out in VB -- it is not the exact same thing, but I think it carries out the same function...

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Monday, April 17, 2006 9:32 PM by Karin
Yeah the ByRef seemed like the best option however I ran into interface implementation issues after that. Thus I'm now doing this part in C#.

One question regarding the line
public class MyReportingService : myServer.ReportExecutionService

What is the myServer a reference to? A web reference of the Reporting Service or some other namespace?

Cheers,
Karin

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, April 18, 2006 4:30 PM by russch
Exactly...It's the reference to the Execution endopoint for SSRS.

# Smorgasbord

Wednesday, May 03, 2006 2:48 AM by Ian Nelson
An eclectic bunch of (mostly techie) bits that don't really deserve a post each:

Here's a really useful...

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, May 25, 2006 5:50 AM by Sam
I have anonnymous access but keep on getting this error when using your code even though I'm logging in as admin. Anyone has any idea why?

{"System.Web.Services.Protocols.SoapException: Logon failed. ---> Microsoft.ReportingServices.Diagnostics.Utilities.LogonFailedException: Logon failed.\n   at Microsoft.ReportingServices.WebServer.RSCustomAuthentication.LogonUser(String userName, String password, String authority)\n   at Microsoft.ReportingServices.WebServer.ReportingService.LogonUser(String userName, String password, String authority)\n   --- End of inner exception stack trace ---\n   at Microsoft.ReportingServices.WebServer.ReportingService.LogonUser(String userName, String password, String authority)"}

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Monday, September 25, 2006 1:54 PM by furmangg
I've got this working fine for viewing reports. But the problem is that the keepalive isn't working. (You know that the ReportViewer control does some stuff behind the scenes which keeps the session alive in the web app hosting ReportViewer in addition to the session on the ReportServer web app. That URL looks like: /Reserved.ReportViewerWebControl.axd?ReportSession=lps4st2it0wks545ahsyl4uv&ControlID=173f16f1-f1d3-43ee-9d9c-0c080aacccd3&Culture=1033&UICulture=1033&ReportStack=1&OpType=SessionKeepAlive&TimerMethod=KeepAliveMethodReportViewerTouchSession0&CacheSeed=Mon%20Sep%2025%2012%3A28%3A24%202006)

If you look in the web.config you see:

<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/>

When I hit that URL I get this error:

System.Web.Services.Protocols.SoapException: Execution 'lps4st2it0wks545ahsyl4uv' cannot be found ---> Microsoft.ReportingServices.Diagnostics.Utilities.ExecutionNotFoundException: Execution 'lps4st2it0wks545ahsyl4uv' cannot be found
 at Microsoft.ReportingServices.WebServer.SessionStarterAction.CreateExisting()
 at Microsoft.ReportingServices.WebServer.ReportExecutionService.GetExecutionInfo(ExecutionInfo& executionInfo)
 --- End of inner exception stack trace ---
 at Microsoft.ReportingServices.WebServer.ReportExecutionService.GetExecutionInfo(ExecutionInfo& executionInfo)

So I'm guessing that the HttpHandler isn't using my credentials. Any thoughts?

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Friday, November 03, 2006 12:03 PM by Grant

Great article and I've almost got it working, however the authcookie is null and the service is returning a SoapException at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse().  When I step through the code, the m_authCookie is always null.  

# The type or namespace name 'ReportExecutionService' could not be found (are you missing a using directive or an assembly reference?)

Monday, November 13, 2006 6:01 AM by Brad

I used the code above, but I always receive the following error message:

"The type or namespace name 'ReportExecutionService' could not be found (are you missing a using directive or an assembly reference?)"

What using reference do I need? Or how can I solve this problem?

thx

# Error Message

Monday, November 13, 2006 8:09 AM by Melanie

Dear Russell,

I also used this code...but the following error message appear: "The server committed a protocol violation. Section=ResponseStatusLine"

I tried to use the the cod ein my web.config, but the error is still there:

<system.net>  

<settings>  

<httpWebRequest UnsafeHeaderParsing "true" />  

</settings>  

</system.net>  

Does anybody have the same problem or does anybody know how I can handle this?

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, January 04, 2007 1:40 AM by sudha

Can you please send me the Details of how to over come this problem Im having the Same Problem

here is my error

System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Logon failed. ---> Microsoft.ReportingServices.Diagnostics.Utilities.LogonFailedException: Logon failed. at Microsoft.ReportingServices.WebServer.RSCustomAuthentication.LogonUser(String userName, String password, String authority) at Microsoft.ReportingServices.WebServer.ReportingService.LogonUser(String userName, String password, String authority) --- End of inner exception stack trace --- at .................

Please help me

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, January 04, 2007 5:54 AM by sudha

Russel

  this authentication is helpful if u render the report using report viewer control but what I want is to render the rdl file. is there any way to do that also?

Thanks in advance

Sudha

# Sql 2005 Reporting Service e autenticazione via form

Tuesday, March 06, 2007 6:10 PM by Alberto Casu

Stiamo in questi giorni migrando una applicazione di un nostro cliente ad una nuova infrastruttura HW

# Sql 2005 Reporting Service e autenticazione via form

Tuesday, March 06, 2007 7:07 PM by Alberto Casu

Stiamo in questi giorni migrando una applicazione di un nostro cliente ad una nuova infrastruttura HW

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Saturday, March 24, 2007 7:58 PM by drew

I am also getting The type or namespace name 'ReportingService' could not be found (are you missing a using directive or an assembly reference?)

Something is not installed perhaps a Reportservices SDK?

msrspbs.20.zdux0012 (at) xoxy.net

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, March 27, 2007 1:31 PM by Horatiu Ripa

I just have my brain bursted:

Is there a way to have an indirection between an WinForm aplication and Reporting Services?

I mean, on client side there's a Winform Report Viewer embed into an application; client of a custom webservice. Is there a way to have Report Viewer to not refer directly the Reporting Services WebSites/Services, but through some kind of custom webservice indirection????

Something like:

[ReportViewer] Get Report -> [Custom WebService] grab the request, process something, forward it to -> [Reporting Services] produces report -> [Custom WebService] grab the response, process something, return it to -> [ReportViewer] render

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Wednesday, March 28, 2007 7:53 AM by russch

Horatui -- No, there is no way to do this. If you want to approximate the same thing, you could go into local mode and populate your dataset via another webservice, then bind it to the control.

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Monday, April 02, 2007 6:16 AM by Horatiu Ripa

Actually, we quite did it...

But this is a workaround to avoid Forms Authentication of WinForm.ReportViewer.

The main problem is that we have a custom authentication for a larger app (windows clients/web serviced), which contains reports. We don't want new pop-ups or whatever for further authentications, once someone is logged in the application it should be able to view the reports.

Is there a way to obtain a RS Form Authentication authCookie from a Windows app and use it instead of passing usr/pwd?

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, May 24, 2007 9:52 AM by adolf garlic

I am getting rsLogonfailed doing the same thing

b.o.o.h.o.o.

:(

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, June 05, 2007 4:20 AM by Satvinder Basra

To pass the autenticated user from ASP.NET 2005 to the SQL Report Server 2005 without passing in the user name and password try....

ReportViewer reportViewer = new ReportViewer();        

ReportViewerCredentials rvc = new ReportViewerCredentials((WindowsIdentity)Page.User.Identity);

               reportViewer.ServerReport.ReportServerCredentials = rvc;

public class ReportViewerCredentials : IReportServerCredentials

{

   WindowsIdentity _userToken;

   public ReportViewerCredentials(WindowsIdentity userToken)

   {

       _userToken = userToken;

   }

   #region IReportServerCredentials Members

   public WindowsIdentity ImpersonationUser

   {

       get

       {

           return _userToken;

       }

   }

   public ICredentials NetworkCredentials

   {

       get

       {

           return null;  // Not using NetworkCredentials to authenticate.

       }

   }

   #endregion

   #region IReportServerCredentials Members

   public bool GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority)

   {

       authCookie = null;

       userName = null;

       password = null;

       authority = null;

       return false;// throw new Exception("The method or operation is not implemented.");

   }

   #endregion

}

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Wednesday, July 18, 2007 9:27 AM by DS

Hi Russell,

When i try running the report in ReportViewer control dragged on one of my webpage, i get the following error:

Client found response content type of '', but expected 'text/xml'. The request failed with an empty response.

(Please note: SSRS works in Forms mode of authentication)

Can you please suggest me the solution for this problem?

Any help would be much appreciated.

Thanks,

DS

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Wednesday, July 18, 2007 10:21 AM by DS

Ignore my previous query. I got resolved it. ReportServerUrl was not set correctly. I had 'localhost' mentioned in it instead of <machinename>

Thanks,

DS

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, November 13, 2007 9:11 PM by Jay

Hi,

I've just recently been messing around with this stuff and can't understand something and thought you can shed some light on it.

I have a network structure where the report server resides on some internal network segment (not internet facing) and my ASP.NET app that needs to serves reports to the clients; the ASP is internet facing.

When I tried to use the ReportViewer control in my app there were a few things that I noticed that didn't make much sense to me.

PROBLE:  When the authentication issued a ticket it needed to translate the Cookie object into HttpCookie object; in the sample code it translated that cookie. In so doing I copied all attributes including the Cookie.Domain object into the HttpCookie (in Login.aspx).

When I did this, the redirect form (Default.aspx) did not contain the cookie in the Request.Cookies collection. When I didn't set this in Login.aspx and set it in Default.aspx it seem to render the report fine. Why does this domain setting remove the cookie from the cookiejar?

Thanks,

Jay.

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, January 31, 2008 10:17 AM by Dilip Shetty

This is a really useful article. Found it after a long search.

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, March 18, 2008 12:48 PM by Krip

EXCELLENT article.  Thanks!

-Krip

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, July 01, 2008 2:47 PM by p

Forms Authentication does not work with Report Viewer. I get Object moved to here error. Help

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, July 10, 2008 7:35 AM by russch

Are you pointing to the real name of your server, or using http://localhost instead. Make sure not to use localhost.

# using forms authentication

Saturday, August 02, 2008 1:31 AM by using forms authentication

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Wednesday, August 27, 2008 11:31 PM by tima

Hey there, I've done exactly what's shown here.

I have form authentication working fine using the microsoft sample but i'm trying to set it up so i can use it with report viewer.

I have the asp page where the reportviewer is and i have a logon page aswell. But when i enter login credentials, it keeps giving this error:

Invalid URI: The format of the URI could not be determined.

its failing at this line:

MyReportingService svc = new MyReportingService();

       svc.Url = "http://reportserv/reportserver/reportexecution2005.asmx";

the link works fine but i don't know what's wrong?! Any help much appreciated :)

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Tuesday, October 28, 2008 11:46 AM by John Foll

I am trying to find out how to get GetUserId function in Report Models to work. It was broken by the Custom Security Extension, like everything else, and I need a fix for it.

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Thursday, November 13, 2008 10:27 AM by Programmer

This worked well....thanks for posting!

# re: Using Forms Authentication with the Report Viewer control and SQL Server Reporting Services 2005

Monday, March 30, 2009 3:53 PM by sri

Actually we are trying to develop a asp.net app in C# for displaying the the ssrs reports. We want to use a tree view and pass the node url's through the database. WE tried using Report viewer but we were unsuccessful. Can any one help us to find a right way to reach the goal.

# Russell Christopher s Semi Useful BI Musings Using Forms | Paid Surveys

# Russell Christopher s Semi Useful BI Musings Using Forms | debt solutions

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker