Exemplo n.º 1
0
        private void CreateSAMLResponse()
        {
            IDProvider config = IDProvider.GetConfig();

            SAMLResponse.ID           = SAMLUtility.GenerateID();
            SAMLResponse.Version      = SAMLUtility.VERSION;
            SAMLResponse.IssueInstant = DateTime.UtcNow.AddMinutes(10);
            SAMLResponse.InResponseTo = SAMLRequest.ID;

            SAMLResponse.Issuer       = new NameIDType();
            SAMLResponse.Issuer.Value = config.id;

            SAMLResponse.Status            = new StatusType();
            SAMLResponse.Status.StatusCode = new StatusCodeType();

            // Atualiza Cookie de sistemas autenticados e configura Status
            HttpCookie cookie = this.Context.Request.Cookies["SistemasLogged"];

            if (cookie != null)
            {
                // Carrega a Entidade SYS_Sistema apartir do caminho de logout
                SYS_Sistema entitySistema = new SYS_Sistema {
                    sis_caminhoLogout = ((NameIDType)SAMLRequest.Item).Value
                };
                if (SYS_SistemaBO.GetSelectBy_sis_caminho(entitySistema, SYS_SistemaBO.TypePath.logout))
                {
                    // Remove o sistema do Cookie
                    cookie.Values.Remove(entitySistema.sis_id.ToString());
                    // Atualiza dados do Cookie
                    this.Context.Response.Cookies.Set(cookie);

                    if (!cookie.Values.AllKeys.Contains(entitySistema.sis_id.ToString()))
                    {
                        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.Success;
                        SAMLResponse.Status.StatusMessage    = "A solicitação foi realizada com sucesso.";
                    }
                    else
                    {
                        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.RequestDenied;
                        SAMLResponse.Status.StatusMessage    = "Não foi possível atender a solicitação, o sistema emissor da requisição não está autenticado.";
                    }
                }
                else
                {
                    SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.RequestDenied;
                    SAMLResponse.Status.StatusMessage    = "Não foi possível atender a solicitação, sistema emissor da requisição não está cadastrado corretamente.";;
                }
            }
            else
            {
                SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.RequestDenied;
                SAMLResponse.Status.StatusMessage    = "Não foi possível atender a solicitação.";
            }

            HttpPostBinding binding = new HttpPostBinding(SAMLResponse, HttpUtility.UrlDecode(this.Context.Request[HttpBindingConstants.RelayState]));

            binding.SendResponse(this.Context, HttpUtility.UrlDecode(this.Context.Request[HttpBindingConstants.RelayState]), SAMLTypeSSO.logout);
        }
Exemplo n.º 2
0
    private void CreateSAMLResponse()
    {
        FormsIdentity id = null;

        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    id = (FormsIdentity)HttpContext.Current.User.Identity;
                }
            }
        }

        DateTime notBefore    = (id != null ? id.Ticket.IssueDate.ToUniversalTime() : DateTime.UtcNow);
        DateTime notOnOrAfter = (id != null ? id.Ticket.Expiration.ToUniversalTime() : DateTime.UtcNow.AddMinutes(30));

        IDProvider config = IDProvider.GetConfig();

        SAMLResponse.Status                  = new StatusType();
        SAMLResponse.Status.StatusCode       = new StatusCodeType();
        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.Success;

        AssertionType assert = new AssertionType();

        assert.ID           = SAMLUtility.GenerateID();
        assert.IssueInstant = DateTime.UtcNow.AddMinutes(10);

        assert.Issuer       = new NameIDType();
        assert.Issuer.Value = config.id;

        SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType();

        subjectConfirmation.Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
        subjectConfirmation.SubjectConfirmationData              = new SubjectConfirmationDataType();
        subjectConfirmation.SubjectConfirmationData.Recipient    = SAMLRequest.Issuer;
        subjectConfirmation.SubjectConfirmationData.InResponseTo = SAMLRequest.Request.ID;
        subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = notOnOrAfter;

        NameIDType nameID = new NameIDType();

        nameID.Format = SAMLUtility.NameIdentifierFormats.Transient;
        nameID.Value  = (id != null ? id.Name : UtilBO.FormatNameFormsAuthentication(this.__SessionWEB.__UsuarioWEB.Usuario));

        assert.Subject       = new SubjectType();
        assert.Subject.Items = new object[] { subjectConfirmation, nameID };

        assert.Conditions                       = new ConditionsType();
        assert.Conditions.NotBefore             = notBefore;
        assert.Conditions.NotOnOrAfter          = notOnOrAfter;
        assert.Conditions.NotBeforeSpecified    = true;
        assert.Conditions.NotOnOrAfterSpecified = true;

        AudienceRestrictionType audienceRestriction = new AudienceRestrictionType();

        audienceRestriction.Audience = new string[] { SAMLRequest.Issuer };
        assert.Conditions.Items      = new ConditionAbstractType[] { audienceRestriction };

        AuthnStatementType authnStatement = new AuthnStatementType();

        authnStatement.AuthnInstant = DateTime.UtcNow;
        authnStatement.SessionIndex = SAMLUtility.GenerateID();

        authnStatement.AuthnContext       = new AuthnContextType();
        authnStatement.AuthnContext.Items =
            new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" };

        authnStatement.AuthnContext.ItemsElementName =
            new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };

        StatementAbstractType[] statementAbstract = new StatementAbstractType[] { authnStatement };
        assert.Items       = statementAbstract;
        SAMLResponse.Items = new object[] { assert };

        string xmlResponse = SAMLUtility.SerializeToXmlString(SAMLResponse);

        XmlDocument doc = new XmlDocument();

        doc.LoadXml(xmlResponse);
        XmlSignatureUtils.SignDocument(doc, assert.ID);
        SAMLResponse = SAMLUtility.DeserializeFromXmlString <ResponseType>(doc.InnerXml);

        HttpPostBinding binding = new HttpPostBinding(SAMLResponse, HttpUtility.UrlDecode(Request[HttpBindingConstants.RelayState]));

        binding.SendResponse(this.Context, HttpUtility.UrlDecode(SAMLRequest.AssertionConsumerServiceURL), SAMLTypeSSO.signon);
    }
Exemplo n.º 3
0
        /// <summary>
        /// Retorna um XmlElement contendo informações do Saml
        /// </summary>
        /// <returns></returns>
        private XmlElement GetElementSAML(bool full)
        {
            // Cria elemento SAML
            XmlElement xmlElementSAML = xml.CreateElement("Saml");

            xmlElementSAML.SetAttribute("type", "Identity Provider");
            xmlElementSAML.SetAttribute("version", SAMLUtility.VERSION);

            // Cria elemento IDProvider
            string     statusIDProvider     = string.Empty;
            XmlElement xmlElementIDProvider = xml.CreateElement("IDProvider");

            xmlElementSAML.AppendChild(xmlElementIDProvider);
            try
            {
                IDProvider config = IDProvider.GetConfig();
                if (config != null)
                {
                    xmlElementIDProvider.SetAttribute("id", config.id);
                    statusIDProvider = StatusBO.Success;
                }
                else
                {
                    statusIDProvider = "Não foi possível encontrar as configurações.";
                }
            }
            catch (Exception ex)
            {
                statusIDProvider = ex.Message;
            }
            xmlElementIDProvider.SetAttribute("status", statusIDProvider);

            if (full)
            {
                // Cria elemento Logged
                string     statusLogged     = string.Empty;
                XmlElement xmlElementLogged = xml.CreateElement("Logged");
                xmlElementSAML.AppendChild(xmlElementLogged);
                try
                {
                    HttpCookie cookie = Context.Request.Cookies["SistemasLogged"];
                    xmlElementLogged.SetAttribute("count", (cookie == null ? "0" : cookie.Values.AllKeys.Count(p => p != null).ToString()));
                    if (cookie != null)
                    {
                        foreach (String str in cookie.Values.AllKeys.Where(p => p != null))
                        {
                            XmlElement xmlElement = xml.CreateElement("Application");
                            xmlElementLogged.AppendChild(xmlElement);
                            xmlElement.SetAttribute("name", cookie.Values[str]);
                        }
                    }
                    statusLogged = StatusBO.Success;
                }
                catch (Exception ex)
                {
                    statusLogged = ex.Message;
                }
                xmlElementLogged.SetAttribute("status", statusLogged);

                // Cria elemento Path
                XmlElement xmlElementPath = xml.CreateElement("Path");
                xmlElementSAML.AppendChild(xmlElementPath);
                try
                {
                    IList <Autenticador.Entities.SYS_Sistema> list          = SYS_SistemaBO.GetSelectBy_usu_id(__SessionWEB.__UsuarioWEB.Usuario.usu_id);
                    Autenticador.Entities.SYS_Sistema         entityCoreSSO = list.Where(p => p.sis_id == ApplicationWEB.SistemaID).First();
                    list.Remove(entityCoreSSO);

                    foreach (Autenticador.Entities.SYS_Sistema entitySistema in list)
                    {
                        string     status     = string.Empty;
                        XmlElement xmlElement = xml.CreateElement("Application");
                        xmlElementPath.AppendChild(xmlElement);
                        xmlElement.SetAttribute("name", entitySistema.sis_nome);
                        xmlElement.SetAttribute("login", entitySistema.sis_caminho);
                        xmlElement.SetAttribute("logout", entitySistema.sis_caminhoLogout);

                        // Validação url de login
                        if (string.IsNullOrEmpty(entitySistema.sis_caminho))
                        {
                            status += "Url de login inválida.";
                        }
                        else if (entitySistema.sis_caminho.Contains(entityCoreSSO.sis_caminho))
                        {
                            status += "A url de login contém um valor possivelmente inválido, que pode entrar em loop ao redirecionar.";
                        }
                        // Validação url de logout
                        if (string.IsNullOrEmpty(entitySistema.sis_caminhoLogout))
                        {
                            status += "Url de logout inválida.";
                        }
                        else if (entitySistema.sis_caminhoLogout.Contains(entityCoreSSO.sis_caminhoLogout))
                        {
                            status += "A url de logout contém um valor possivelmente inválido, que pode entrar em loop ao redirecionar.";
                        }

                        if (string.IsNullOrEmpty(status))
                        {
                            status = StatusBO.Success;
                        }
                        xmlElement.SetAttribute("status", status);
                    }
                }
                catch (Exception ex)
                {
                    xmlElementPath.SetAttribute("error", ex.Message);
                }
            }

            return(xmlElementSAML);
        }