Subject: IDP SingleSignOnService.aspx onload error
Date: 2013-07-09 10:19:55
From: Charan M G
Source: idp-singlesignonservice-aspx-onload-error
----------------------------------------------------------------------

Hi Team,

I am getting object reference not set to an instance of an object in SingleSignOnService.aspx.cs page.

in the line string referer = this.Request.UrlReferrer.AbsoluteUri;

Which means its not able to get my SP redirect url. Please look for the below code:

SingleSignOnService.aspx.cs

"[code lang='C#']

protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Look up for the SP ID
                string referer = this.Request.UrlReferrer.AbsoluteUri;
                int i = -1;
                if (!referer.StartsWith(Services.LocalUri))
                {
                    for (i = 0; i < Services.AllowedServiceUrls.Length; i++)
                    {
                        string url = Services.AllowedServiceUrls[i];

                        if (referer.StartsWith(url))
                            break;
                    }

                    if (i == Services.AllowedServiceUrls.Length)
                        throw new Exception("Your SP is not allowed");
                }

                // Get the saved SSO state, if any.
                // If there isn't saved state then receive the authentication request.
                // If there is saved state then we've just completed a local login in response
                // to a prior authentication request.
                SsoAuthnState ssoState = (SsoAuthnState)Session[SsoSessionKey];

                // Receive the authentication request.
                AuthnRequest authnRequest = null;
                string relayState = null;

                if (i != -1)
                {
                    Util.ReceiveAuthnRequest(this, out authnRequest, out relayState);

                    if (authnRequest == null)
                    {
                        // No authentication request found.
                        return;
                    }
                }

                if (ssoState == null)
                {
                    // Process the authentication request.
                    bool forceAuthn = authnRequest.ForceAuthn;
                    bool allowCreate = false;

                    if (authnRequest.NameIdPolicy != null)
                    {
                        allowCreate = authnRequest.NameIdPolicy.AllowCreate;
                    }

                    ssoState = new SsoAuthnState();
                    ssoState.AuthnRequest = authnRequest;
                    ssoState.RelayState = relayState;
                    ssoState.IdpProtocolBinding = SamlBindingUri.UriToBinding(authnRequest.ProtocolBinding);
                    ssoState.AssertionConsumerServiceURL = authnRequest.AssertionConsumerServiceUrl;

                    // Determine whether or not a local login is required.
                    bool requireLocalLogin = false;

                    if (forceAuthn)
                    {
                        requireLocalLogin = true;
                    }
                    else
                    {
                        if (!User.Identity.IsAuthenticated & allowCreate)
                        {
                            requireLocalLogin = true;
                        }
                    }

                    // If a local login is required then save the authentication request
                    // and initiate a local login.
                    if (requireLocalLogin)
                    {
                        // Save the SSO state.
                        Session[SsoSessionKey] = ssoState;

                        // Initiate a local login.
                        System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                        return;
                    }

                }

                // Create a SAML response with the user's local identity, if any.
                ComponentPro.Saml2.Response samlResponse = Util.CreateSamlResponse(this);

                if (i != -1)
                    // Update the Relay state before sending SAML response.
                    // Dynamically update the assertion consumer service URL corresponding to the service provider.
                    ssoState.AssertionConsumerServiceURL = authnRequest.AssertionConsumerServiceUrl;

                // Send the SAML response to the service provider.
                Util.SendSamlResponse(this, samlResponse, ssoState);
            }

            catch (Exception exception)
            {
                Trace.Write("IdentityProvider", "An Error occurred", exception);
            }
        }

[/code]"

This OnLoad method is called from the Page_Load method of my SP application. Here is the below code

Login.aspx.cs

"[code lang='C#']

string idpToSPBindingList = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
        string spToIdPBindingList = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";

        protected void Page_Load(object sender, EventArgs e)
        {
            // Create the authentication request.
            AuthnRequest authnRequest = BuildAuthenticationRequest();

            // Create and cache the relay state so we remember which SP resource the user wishes
            // to access after SSO.
            string spResourceUrl = Util.GetAbsoluteUrl(this, FormsAuthentication.GetRedirectUrl("", false));
            string relayState = Guid.NewGuid().ToString();
            SamlSettings.CacheProvider.Insert(relayState, spResourceUrl, new TimeSpan(1, 0, 0));

            // Send the authentication request to the identity provider over the selected binding.
            string idpUrl = string.Format("{0}?{1}={2}", WebConfigurationManager.AppSettings["SingleSignonIdProviderUrl"], Util.BindingVarName, HttpUtility.UrlEncode(spToIdPBindingList));

            switch (spToIdPBindingList)
            {
                case SamlBindingUri.HttpRedirect:
                    X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPCertKey];

                    authnRequest.Redirect(Response, idpUrl, relayState, x509Certificate.PrivateKey);
                    break;

                case SamlBindingUri.HttpPost:
                    authnRequest.SendHttpPost(Response, idpUrl, relayState);

                    // Don't send this form.
                    Response.End();
                    break;

                case SamlBindingUri.HttpArtifact:
                    // Create the artifact.
                    string identificationUrl = Util.GetAbsoluteUrl(this, "~/");
                    Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(SamlArtifact.GetSourceId(identificationUrl), SamlArtifact.GetHandle());

                    // Cache the authentication request for subsequent sending using the artifact resolution protocol.
                    SamlSettings.CacheProvider.Insert(httpArtifact.ToString(), authnRequest.GetXml(), new TimeSpan(1, 0, 0));

                    // Send the artifact.
                    httpArtifact.Redirect(Response, idpUrl, relayState);
                    break;
            }
        }

/// <summary>
        /// Builds an authentication request.
        /// </summary>
        /// <returns>The authentication request.</returns>
        private AuthnRequest BuildAuthenticationRequest()
        {
            // Create some URLs to identify the service provider to the identity provider.
            // As we're using the same endpoint for the different bindings, add a query string parameter
            // to identify the binding.
            string issuerUrl = Util.GetAbsoluteUrl(this, "~/");
            string assertionConsumerServiceUrl = string.Format("{0}?{1}={2}", Util.GetAbsoluteUrl(this, "~/AssertionService.aspx"), Util.BindingVarName, HttpUtility.UrlEncode(idpToSPBindingList));

            // Create the authentication request.
            AuthnRequest authnRequest = new AuthnRequest();
            authnRequest.Destination = WebConfigurationManager.AppSettings["SingleSignonIdProviderUrl"];
            authnRequest.Issuer = new Issuer(issuerUrl);
            authnRequest.ForceAuthn = false;
            authnRequest.NameIdPolicy = new NameIdPolicy(null, null, true);
            authnRequest.ProtocolBinding = idpToSPBindingList;
            authnRequest.AssertionConsumerServiceUrl = assertionConsumerServiceUrl;

            // Don't sign if using HTTP redirect as the generated query string is too long for most browsers.
            if (spToIdPBindingList != SamlBindingUri.HttpRedirect)
            {
                // Sign the authentication request.
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPCertKey];

                authnRequest.Sign(x509Certificate);
            }
            return authnRequest;

        }

protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            string error = Request.QueryString[Util.ErrorVarName];
            if (error == null)
                error = string.Empty;

            // Display any error message resulting from a failed login if any.
            lblErrorMessage.Text = error;

        }

[/code]"

The same code is working fine if my Page_Load definition is inside a button click event.

But I want this to be done on Page_Load event.

Please help me out on this error.

Regards,

Charan M G

---------------------------------------------------------------------- Note: This question has been asked on the Q&A forum of Thang Dang's fraudulent ComponentPro brand If you purchased anything from ComponentPro, you have been scammed. Contact the payment processor who sold you the license and ask for your money back. Back to ComponentPro Q&A Forum Index