Tech Off Thread

7 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Urgent please, I dare you to help me fix this very strange problem on impersonation with reportviewe

Back to Forum: Tech Off
  • User profile image
    levalencia

    Hello guys I expect somebody to help me with this strange problem.

    I have a web application, with reportviewer to show reports, I downloaded some code to make the impersonation, very difficult code.

    From my development machine I can browse the reports without problems, when I create an installer and install it on the testing machine I got this error. 

    http://www.avansoft.net/~levalencia/2.gif

    The translation to english would be. (Translated using google)

    An error when creating has taken place the controller of section of configuration for system.web/webServices: Error when trying to supplant. It cannot continue the execution of this request.  Error when trying to supplant. It cannot continue the execution of this request.

    The development machine has windows 2000 pro the server has windows 2003, in the same machine there its IIS and sql 2005 with Reporting Services.

     

    The code of the pages where I use the reports is the folllowing one.

    How should I configure the security of the servers or virtual directories, Please help me somebody from MSFT as I am worried about it.


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                cargarReporte();
            }
        }

        private void cargarReporte()
        {
            string usuario = ConfigurationSettings.AppSettings["Usuario"].ToString();
            string clave = ConfigurationSettings.AppSettings["Clave"].ToString();
            string dominio = ConfigurationSettings.AppSettings["Dominio"].ToString();

            string reportserver = ConfigurationSettings.AppSettings["ReportServer"].ToString();
            string reportfolder = ConfigurationSettings.AppSettings["ReportFolder"].ToString();

            int NmCiclo = Convert.ToInt32(Request.QueryString["NmCiclo"]);
            int NmEmpresa = Convert.ToInt32(Request.QueryString["NmEmpresa"]);
            int NmCargoEvaluada = Convert.ToInt32(Request.QueryString["NmCargoEvaluada"]);
            int NmPersonaEvaluada = Convert.ToInt32(Request.QueryString["NmPersonaEvaluada"]);

            rptViewer.ServerReport.ReportServerUrl = new Uri(reportserver);
            rptViewer.ServerReport.ReportPath = reportfolder + "RPT_ClasificaciondeCompetencias";
            x.ReportViewerCredentials rvwCreds = new x.ReportViewerCredentials(usuario, clave, dominio);
            rptViewer.ServerReport.ReportServerCredentials = rvwCreds;
        }


        protected void rptViewer_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                string usuario = ConfigurationSettings.AppSettings["Usuario"].ToString();
                string clave = ConfigurationSettings.AppSettings["Clave"].ToString();
                string dominio = ConfigurationSettings.AppSettings["Dominio"].ToString();
               
                x.ReportViewerCredentials rvwCreds = new x.ReportViewerCredentials(usuario, clave, dominio);
                rptViewer.ServerReport.ReportServerCredentials = rvwCreds;
            }
        }

     

     

    And the class I downloaded from the Internet is the following one.

     

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using Microsoft.Reporting.WebForms;
    using System.Net;
    using System.Security.Principal;
    using System.Runtime.InteropServices;

    /// <summary>
    /// Summary description for ReportViewerCredentials
    /// </summary>
    namespace x
    {
        public class ReportViewerCredentials : IReportServerCredentials
        {
            [DllImport("advapi32.dll", SetLastError = true)]
            public extern static bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            public extern static bool CloseHandle(IntPtr handle);

            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
                int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

            public ReportViewerCredentials()
            {
            }

            public ReportViewerCredentials(string username)
            {
                this.Username = username;
            }


            public ReportViewerCredentials(string username, string password)
            {
                this.Username = username;
                this.Password = password;
            }


            public ReportViewerCredentials(string username, string password, string domain)
            {
                this.Username = username;
                this.Password = password;
                this.Domain = domain;
            }


            public string Username
            {
                get
                {
                    return this.username;
                }
                set
                {
                    string username = value;
                    if (username.Contains("\\"))
                    {
                        this.domain = username.Substring(0, username.IndexOf("\\"));
                        this.username = username.Substring(username.IndexOf("\\") + 1);
                    }
                    else
                    {
                        this.username = username;
                    }
                }
            }
            private string username;

     

            public string Password
            {
                get
                {
                    return this.password;
                }
                set
                {
                    this.password = value;
                }
            }
            private string password;


            public string Domain
            {
                get
                {
                    return this.domain;
                }
                set
                {
                    this.domain = value;
                }
            }
            private string domain;

     


            #region IReportServerCredentials Members

            public bool GetBasicCredentials(out string basicUser, out string basicPassword, out string basicDomain)
            {
                basicUser = username;
                basicPassword = password;
                basicDomain = domain;
                return username != null && password != null && domain != null;
            }

            public bool GetFormsCredentials(out string formsUser, out string formsPassword, out string formsAuthority)
            {
                formsUser = username;
                formsPassword = password;
                formsAuthority = domain;
                return username != null && password != null && domain != null;

            }

            public bool GetFormsCredentials(out Cookie authCookie,
          out string user, out string password, out string authority)
            {
                authCookie = null;
                user = password = authority = null;
                return false;  // Not implemented
            }


            public WindowsIdentity ImpersonationUser
            {
                get
                {

                    string[] args = new string[3] { this.Domain.ToString(), this.Username.ToString(), this.Password.ToString() };
                    IntPtr tokenHandle = new IntPtr(0);
                    IntPtr dupeTokenHandle = new IntPtr(0);

                    const int LOGON32_PROVIDER_DEFAULT = 0;
                    //This parameter causes LogonUser to create a primary token.
                    const int LOGON32_LOGON_INTERACTIVE = 2;
                    const int SecurityImpersonation = 2;

                    tokenHandle = IntPtr.Zero;
                    dupeTokenHandle = IntPtr.Zero;
                    try
                    {
                        // Call LogonUser to obtain an handle to an access token.
                        bool returnValue = LogonUser(args[1], args[0], args[2],
                            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                            ref tokenHandle);

                        if (false == returnValue)
                        {
                            Console.WriteLine("LogonUser failed with error code : {0}",
                                Marshal.GetLastWin32Error());
                            return null;
                        }

                        // Check the identity.
                        System.Diagnostics.Trace.WriteLine("Before impersonation: "
                            + WindowsIdentity.GetCurrent().Name);


                        bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
                        if (false == retVal)
                        {
                            CloseHandle(tokenHandle);
                            Console.WriteLine("Exception in token duplication.");
                            return null;
                        }


                        // The token that is passed to the following constructor must
                        // be a primary token to impersonate.
                        WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
                        WindowsImpersonationContext impersonatedUser = newId.Impersonate();


                        // Free the tokens.
                        if (tokenHandle != IntPtr.Zero)
                            CloseHandle(tokenHandle);
                        if (dupeTokenHandle != IntPtr.Zero)
                            CloseHandle(dupeTokenHandle);

                        // Check the identity.
                        System.Diagnostics.Trace.WriteLine("After impersonation: "
                            + WindowsIdentity.GetCurrent().Name);

                        return newId;

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception occurred. " + ex.Message);
                    }

                    return null;
                }
            }

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


            #endregion
        }
    }

     

     

     

  • User profile image
    figuerres

    I do not have the code at home with me but I think you are using some code from the beta relase that you do not need now.

    you are trying to use a windows client to view the report??

    if so I can get a sample later tongihht or in the morning that works.

    I have a web site that shows reports and a windows app that shows reports. I have working code for each.

  • User profile image
    levalencia

    Its a website not a windows form

    The working code you have is for impersonation??

  • User profile image
    jmbledsoe

    levalencia wrote:
    An error when creating has taken place the controller of section of configuration for system.web/webServices: Error when trying to supplant. It cannot continue the execution of this request.  Error when trying to supplant. It cannot continue the execution of this request.


    This sounds to me like something wrong with your web.config file, in the system.web/webServices element.  When you get the error while running locally on the testing machine, does it highlight an element or line in the web.config?

  • User profile image
    levalencia

    I dont have webservices on my website.

    this is my web.config

    <?xml version="1.0"?>

    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

    <appSettings>

    <add key="Autenticacion" value="SQL"/>

    <add key="sqlconn" value="Data Source=agamenon;Initial Catalog=GescomDllo;User id=ejecucionasp; Password=xxx; connection reset=false;connection lifetime=5; min pool size=1; max pool size=500"/>

    <add key="ReportServer" value="http://agamenon:90/ReportServer"/>

    <add key="ReportFolder" value="/GescomRpts/"/>

    <add key="Usuario" value="levalencia"/>

    <add key="Clave" value="xxxx"/>

    <add key="Dominio" value="se"/>

    <add key="ReportServerEndPoint" value="http://agamenon:90/ReportServer/"/>

    </appSettings>

    <connectionStrings>

    <add name="sqlconn" connectionString="Data Source=agamenon;Initial Catalog=GescomDllo;User id=ejecucionasp; Password=xxx"/>

    <add name="ADConnString" connectionString="LDAP://192.xxx.1.14:389/OU=Medell¡n,DC=SE,DC=NET"/>

    </connectionStrings>

    <system.web>

    <pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never"/>

    <httpHandlers>

    <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"/>

    </httpHandlers>

    <identity impersonate="true"/>

    <compilation debug="true">

    <assemblies>

    <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

    <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

    <add assembly="System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

    <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

    <add assembly="Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies>

    <buildProviders>

    <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

    </buildProviders>

    </compilation>

    <globalization culture="es-CO" requestEncoding="utf-8" responseEncoding="utf-8"/>

    <siteMap defaultProvider="SiteMapSecuritySample" enabled="true">

    <providers>

    <add name="SiteMapSecuritySample" description="Proveedor de seguridad para la jerarquia de navegacion del sitio con roles." type="System.Web.XmlSiteMapProvider" securityTrimmingEnabled="true" siteMapFile="Web.sitemap"/>

    </providers>

    </siteMap>

    <roleManager enabled="true" defaultProvider="SqlRoleManager" cacheRolesInCookie="true" cookieTimeout="30" cookieRequireSSL="false" createPersistentCookie="true">

    <providers>

    <add name="SqlRoleManager" type="GescomSeguridad.RoleSql" connectionStringName="MySqlConnection" applicationName="Gescom"/>

    </providers>

    </roleManager>

    <membership defaultProvider="SecuritySQL" userIsOnlineTimeWindow="15">

    <providers>

    <add name="SecuritySQL" type="GescomSeguridad.ProveedorSQL" connectionStringName="sqlconn" applicationName="Gescom" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Clear"/>

    <add name="SecurityLDAP" type="GescomSeguridad.ProveedorLDAP" attributeMapUsername="SAMAccountName" connectionStringName="ADConnString"/>

    </providers>

    </membership>

    <authentication mode="Forms">

    <forms name=".ASPXAUTH" defaultUrl="default.aspx" loginUrl="login.aspx" protection="All" timeout="30" path="/" requireSSL="false" slidingExpiration="true" cookieless="UseDeviceProfile" enableCrossAppRedirects="false">

    </forms>

    </authentication>

    <authorization>

    <allow users="*"/>

    </authorization>

    <customErrors mode="Off" defaultRedirect="ErrDefault.aspx">

    <error statusCode="401" redirect="ErrNoAutorizado.aspx"/>

    <error statusCode="404" redirect="ErrPaginaNoEncontrada.aspx"/>

    <error statusCode="500" redirect="ErrServidor.htm"/>

    </customErrors>

    <!--<pages enableEventValidation="false" />-->

    </system.web>

    <location path="~/Protected/01_Administradores">

    <system.web>

    <authorization>

    <allow roles="Administradores"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <location path="~/Protected/02_Evaluadores">

    <system.web>

    <authorization>

    <allow roles="Evaluadores"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <location path="~/Protected/03_Planeadores">

    <system.web>

    <authorization>

    <allow roles="Planeador"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <location path="~/Protected/03_EvaluadoresEficacia">

    <system.web>

    <authorization>

    <allow roles="EvaluadoresEficacia"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <location path="~/Protected/04_Retroalimentadores">

    <system.web>

    <authorization>

    <allow roles="Retroalimentadores"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <location path="~/Protected/05_ConsultorParcial">

    <system.web>

    <authorization>

    <allow roles="ConsultorParcial"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <location path="~/Protected/06_ConsultorTotal">

    <system.web>

    <authorization>

    <allow roles="ConsultorTotal"/>

    <deny users="*"/>

    </authorization>

    </system.web>

    </location>

    <!-- other configuration settings here -->

    </configuration>

  • User profile image
    cheong

    Basically, when I see this error, I'll begin check the permission set on "%windir%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files"

    Try to see if your impersonated user have right to write in here.

    Recent Achievement unlocked: Code Avenger Tier 4/6: You see dead program. A lot!
    Last modified
  • User profile image
    levalencia

    It didnt have permissions, anyway I gave it permissions but the error is still there.

     

     

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.