Example #1
0
        private void Original()
        {
            // Set Relay State
            RelayState.Value = "http://www.davidsp8.com";
            // Set Attrs
            Dictionary <string, string> attrs = new Dictionary <string, string>();

            attrs.Add("Email", Session["Email"].ToString());
            // Set SAML Response
            SAMLResponse.Value =
                SamlHelper.GetPostSamlResponse(
                    "http://www.davidsp8.com/SSO.asmx",
                    "davidsp8.com:sp",
                    "davidsp8.com",
                    "localuserid",
                    StoreLocation.LocalMachine, StoreName.Root, X509FindType.FindByThumbprint, null, null,
                    "41fe9204effd0d8c5e65a1de3a507da1383fd14f", attrs);

            //Set Form Action
            this.frmSSO.Action = "http://www.davidsp8.com/SSO.asmx";

            // Add OnLoad Logic so that form will be submitted.
            HtmlGenericControl body = (HtmlGenericControl)this.Page.FindControl("bodySSO");

            if (body != null)
            {
                body.Attributes.Add("onload", "document.forms.frmSSO.submit();");
            }
        }
Example #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["SAMLResponse"] != null)
            {
                byte[] responseData = Convert.FromBase64String(Request.Form["SAMLResponse"]);
                string xmlString    = Encoding.UTF8.GetString(responseData);

                SAMLResponse.InnerText = xmlString;

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.LoadXml(xmlString);

                SamlResponseResult result = SamlHelper.CheckAndGetUserIDResponseDoc(xmlDoc);

                this.ResponseUserID.Text = result.UserID;
                FormsAuthentication.SetAuthCookie(result.UserID, false);

                if (result.ReturnUrl.IsNotEmpty())
                {
                    this.Response.Redirect(result.ReturnUrl);
                }
                else
                {
                    this.Response.Redirect("../list/AllEvents.aspx");
                }
            }
        }
Example #3
0
        public AuthController(IUserService userService, IAffiliateService affiliateService, ICmsService cmsService, ILogger logger)
        {
            _cmsService       = cmsService;
            _userService      = userService;
            _affiliateService = affiliateService;
            _logger           = logger;

            SamlHelper.CheckConfiguration();
        }
Example #4
0
        public string GetDeflateEndodedSamlAuthnRequest()
        {
            var authnRequest = SamlHelper.GetSamlAuthnRequest(_httpContext, _serviceProvider.Value);

            XmlDocument requestXml = SamlHelper.ConvertModelToXml(authnRequest);

            string encodedRequest = SecurityHelper.DeflateEncode(requestXml.OuterXml);

            return(encodedRequest);
        }
        public ActionResult SpidRequest(string idpName)
        {
            // Clear user info
            HttpContext.Session.SetObject <UserInfo>("UserInfo", null);

            try
            {
                // Create the SPID request id
                string spidAuthnRequestId = Guid.NewGuid().ToString();

                // Select the Identity Provider
                IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName);

                // Retrieve the signing certificate
                var certificate = X509Helper.GetCertificateFromStore(
                    StoreLocation.LocalMachine, StoreName.My,
                    X509FindType.FindBySubjectName,
                    _configuration["Spid:CertificateName"],
                    validOnly: false);

                // Create the signed SAML request
                var spidAuthnRequest = SamlHelper.BuildAuthnPostRequest(
                    uuid: spidAuthnRequestId,
                    destination: idp.EntityID,
                    consumerServiceURL: _configuration["Spid:DomainValue"],
                    securityLevel: 1,
                    certificate: certificate,
                    identityProvider: idp,
                    enviroment: _env.EnvironmentName == "Development" ? 1 : 0);

                ViewData["data"]   = spidAuthnRequest;
                ViewData["action"] = idp.SingleSignOnServiceUrl;

                //// Save the IdP label and SPID request id as a cookie
                //HttpCookie cookie = Request.Cookies.Get(SPID_COOKIE) ?? new HttpCookie(SPID_COOKIE);
                //cookie.Values["IdPName"] = idpName;
                //cookie.Values["SpidAuthnRequestId"] = spidAuthnRequestId;
                //cookie.Expires = DateTime.Now.AddMinutes(20);
                //Response.Cookies.Add(cookie);

                // Save the IdPName and SPID request id
                this.SetCookie("IdPName", idpName, 20);
                this.SetCookie("SpidAuthnRequestId", spidAuthnRequestId, 20);

                // Send the request to the Identity Provider
                return(View("PostData"));
            }
            catch (Exception ex)
            {
                // TODO: log.Error("Error on HomeController SpidRequest", ex);
                ViewData["Message"]      = "Errore nella preparazione della richiesta di autenticazione da inviare al provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
Example #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.User != null && this.User.Identity != null)
            {
                identity.Text = this.User.Identity.Name;
            }

            W3IssuerConfigurationElement issuerElement = W3Settings.GetSettings().GetSelectedIssuer();

            byte[] samlReq = Encoding.UTF8.GetBytes(SamlHelper.GetSignedRequestDoc(issuerElement.IssuerID, string.Empty, this.Request.Url.ToString()).OuterXml);
            SAMLRequest.InnerText = Convert.ToBase64String(samlReq);
        }
Example #7
0
        public ActionResult Logout(IFormCollection formCollection)
        {
            // Try to get logout request data
            string idPName             = this.GetCookie("IdPName");
            string spidLogoutRequestId = this.GetCookie("SpidLogoutRequestId");

            // End the session and remove cookies
            HttpContext.Session.SetObject <UserInfo>("UserInfo", null);
            this.RemoveCookie("IdPName");
            this.RemoveCookie("SpidAuthnRequestId");
            this.RemoveCookie("SpidLogoutRequestId");
            this.RemoveCookie("SubjectNameId");
            this.RemoveCookie("AuthnStatementSessionIndex");

            // The single logout process can be started directly by IdP provider without a client request done from this service
            // So an empty spidLogoutRequestId is still valid and do not represent an error.
            // In that context, we simply skip the response processing, since there isn't any response to check.
            if (!string.IsNullOrWhiteSpace(spidLogoutRequestId))
            {
                try
                {
                    IdpLogoutResponse idpLogoutResponse = SamlHelper.GetLogoutResponse(formCollection["SAMLResponse"].ToString());

                    if (!idpLogoutResponse.IsSuccessful)
                    {
                        // TODO: log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP riporta il seguente StatusCode: {idpLogoutResponse.StatusCodeInnerValue} con StatusMessage: {idpLogoutResponse.StatusMessage} e StatusDetail: {idpLogoutResponse.StatusDetail}.");
                        ViewData["Message"]      = "La richiesta di logout è stata rifiutata.";
                        ViewData["ErrorMessage"] = $"StatusCode: {idpLogoutResponse.StatusCodeInnerValue} con StatusMessage: {idpLogoutResponse.StatusMessage} e StatusDetail: {idpLogoutResponse.StatusDetail}.";
                        return(View("Error"));
                    }

                    // Verifica la corrispondenza del valore di spidLogoutRequestId ricavato da cookie con quello restituito dalla risposta
                    if (!SamlHelper.ValidLogoutResponse(idpLogoutResponse, spidLogoutRequestId))
                    {
                        // TODO: log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP non è valida (InResponseTo != spidLogoutRequestId).");
                        ViewData["Message"]      = "La risposta dell'IdP non è valida perché non corrisponde alla richiesta.";
                        ViewData["ErrorMessage"] = $"RequestId: _{spidLogoutRequestId}, InResponseTo: {idpLogoutResponse.InResponseTo}.";
                        return(View("Error"));
                    }
                }

                catch (Exception ex)
                {
                    // TODO: log.Error("Error on ACSController [HttpPost]Index method", ex);
                    ViewData["Message"]      = "Errore nella lettura della risposta ricevuta dal provider.";
                    ViewData["ErrorMessage"] = ex.Message;
                    return(View("Error"));
                }
            }

            return(View("Logout"));
        }
Example #8
0
        public void SamlResponseTest()
        {
            string responseString = ResourceHelper.LoadStringFromResource(Assembly.GetExecutingAssembly(), "MCS.Library.Cloud.W3.Test.Resources.samlResponse.xml");

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(responseString);

            bool validateResult = false;

            Console.WriteLine(SamlHelper.ValidateAndGetUserIDResponseDoc(xmlDoc, out validateResult));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string returnUrl = this.Request.Url.ToString();

            string xml = SamlHelper.GetSignedRequestDoc("www.huaweiams.com", string.Empty, returnUrl).OuterXml;

            SAMLRequestXml.InnerText = xml;

            byte[] samlReq = Encoding.UTF8.GetBytes(xml);
            SAMLRequest.InnerText = Convert.ToBase64String(samlReq);

            privateCAInfo.InnerText = SamlHelper.GetEmbededPrivateCertificate().ToString();
        }
Example #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            loginForm.Action = W3Settings.GetSettings().SignInUri;

            W3IssuerConfigurationElement issuerElement = W3Settings.GetSettings().GetSelectedIssuer();

            string returnUrl = this.Request.QueryString["ReturnUrl"];

            string xml = SamlHelper.GetSignedRequestDoc(issuerElement.IssuerID, string.Empty, returnUrl).OuterXml;

            byte[] samlReq = Encoding.UTF8.GetBytes(xml);
            SAMLRequest.InnerText = Convert.ToBase64String(samlReq);
        }
Example #11
0
        public (string, string) GetUsernameAndAuthIdFromBase64EncodedString(StringValues base64EncodedResponse)
        {
            string       decodedResponse = SecurityHelper.DecodeFromBase64(base64EncodedResponse);
            XmlDocument  xmlResponseWithEncryptedAssertion = SamlHelper.GetXmlFromString(decodedResponse);
            ResponseType responseWithEncryptedAssertion    = SamlHelper.ConvertXmlToModel <ResponseType>(xmlResponseWithEncryptedAssertion);

            SamlValidationHelper.VerifyResponse(responseWithEncryptedAssertion);

            XmlDocument   xmlAssertion = SecurityHelper.DecryptAssertion(xmlResponseWithEncryptedAssertion);
            AssertionType assertion    = SamlHelper.ConvertXmlToModel <AssertionType>(xmlAssertion);

            SamlValidationHelper.ValidateAssertion(assertion, _serviceProvider.Value);

            return(SamlHelper.Username, SamlHelper.AuthnRequestID);
        }
Example #12
0
        public ActionResult SpidRequest(string idpName)
        {
            try
            {
                // Create the SPID request id
                string spidAuthnRequestId = Guid.NewGuid().ToString();

                // Select the Identity Provider
                IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName);

                // Retrieve the signing certificate
                var certificate = X509Helper.GetCertificateFromStore(
                    StoreLocation.LocalMachine, StoreName.My,
                    X509FindType.FindBySubjectName,
                    ConfigurationManager.AppSettings["SPID_CERTIFICATE_NAME"],
                    validOnly: false);

                // Create the signed SAML request
                var spidAuthnRequest = SamlHelper.BuildAuthnPostRequest(
                    uuid: spidAuthnRequestId,
                    destination: idp.EntityID,
                    consumerServiceURL: ConfigurationManager.AppSettings["SPID_DOMAIN_VALUE"],
                    securityLevel: 1,
                    certificate: certificate,
                    identityProvider: idp,
                    enviroment: ConfigurationManager.AppSettings["ENVIROMENT"] == "dev" ? 1 : 0);

                ViewData["data"]   = spidAuthnRequest;
                ViewData["action"] = idp.SingleSignOnServiceUrl;

                // Save the IdP label and SPID request id as a cookie
                HttpCookie cookie = Request.Cookies.Get(SPID_COOKIE) ?? new HttpCookie(SPID_COOKIE);
                cookie.Values["IdPName"]            = idpName;
                cookie.Values["SpidAuthnRequestId"] = spidAuthnRequestId;
                cookie.Expires = DateTime.Now.AddMinutes(20);
                Response.Cookies.Add(cookie);

                // Send the request to the Identity Provider
                return(View("PostData"));
            }
            catch (Exception ex)
            {
                log.Error("Error on HomeController SpidRequest", ex);
                ViewData["Message"]      = "Errore nella preparazione della richiesta di autenticazione da inviare al provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
        private ActionResult SignInUserLocally(string userName, IDictionary <string, string> attributes)
        {
            SamlPocTraceListener.Log("SAML", "SamlController.SignInUserLocally: Sign in user locally.");

            // Extract user email
            var email = SamlHelper.ExtractUserEmailFromSamlAttributes(userName, attributes);
            var user  = _authenticationService.FindUser(UserManager, email);

            if (user == null)
            {
                SamlPocTraceListener.Log("SAML", $"SamlController.SignInUserLocally: Register new user: {userName} with email {email}");

                // Register new user
                user = new ApplicationUser {
                    UserName = userName, Email = email
                };
                var result = UserManager.Create(user, userName); // Use fake password

                if (!result.Succeeded)
                {
                    var errors = string.Join("\r\n", result.Errors);

                    SamlPocTraceListener.Log(
                        "SAML",
                        $"SamlController.SignInUserLocally: Error while registering user: {errors}");

                    return(View("Error"));
                }
            }
            else
            {
                SamlPocTraceListener.Log("SAML", $"SamlController.SignInUserLocally: Found existing user: {userName}");
            }

            // There might be no attributes
            attributes = attributes ?? new Dictionary <string, string>();

            _authenticationService.Authenticate(
                AuthenticationType.Saml,
                email,
                password: userName, // Use fake password
                additionalClaims: attributes);

            return(null);
        }
Example #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var postAction    = "http://localhost/WebServiceProvider/SamlValidate";
            var binFolderPath = Server.MapPath("bin");

            // Set Relay State
            RelayState.Value = "http://localhost/WebServiceProvider";

            // Set Attrs
            Dictionary <string, string> attrs = new Dictionary <string, string>();

            attrs.Add("email", Session["email"].ToString());
            attrs.Add("firstname", Session["firstname"].ToString());
            attrs.Add("lastname", Session["lastname"].ToString());

            // Set SAML Response
            SAMLResponse.Value =
                SamlHelper.GetPostSamlResponse(
                    postAction,
                    "LoanDepot.com:sp",
                    "LoanDepot.com",
                    "localUseridToMapBack",
                    StoreLocation.LocalMachine,
                    StoreName.Root,
                    X509FindType.FindByThumbprint,
                    Path.Combine(binFolderPath, "modotech-test-cert.pfx"),
                    "123456789",
                    "",
                    attrs);

            //Set Form Action
            this.frmSSO.Action = postAction;

            // Add OnLoad Logic so that form will be submitted.
            HtmlGenericControl body = (HtmlGenericControl)this.Page.FindControl("bodySSO");

            if (body != null)
            {
                body.Attributes.Add("onload", "document.forms.frmSSO.submit();");
            }
        }
Example #15
0
        public ActionResult Logout(FormCollection formCollection)
        {
            string IdPName;
            string spidLogoutRequestId;

            // Try to get auth requesta data from cookie
            HttpCookie cookie = Request.Cookies[SPID_COOKIE];

            if (cookie != null)
            {
                IdPName             = cookie["IdPName"];
                spidLogoutRequestId = cookie["SpidLogoutRequestId"];
                log.Info($"Cookie {SPID_COOKIE} IdPName: {IdPName}, SpidLogoutRequestId: {spidLogoutRequestId}");
            }
            else
            {
                log.Error("Error on ACSController [HttpPost]Index method: Impossibile recuperare l'Id della sessione.");
                ViewData["Message"] = "Impossibile recuperare i dati della sessione (cookie scaduto).";
                return(View("Error"));
            }

            // Remove the cookie
            cookie.Values["IdPName"]                    = string.Empty;
            cookie.Values["SpidAuthnRequestId"]         = string.Empty;
            cookie.Values["SpidLogoutRequestId"]        = string.Empty;
            cookie.Values["SubjectNameId"]              = string.Empty;
            cookie.Values["AuthnStatementSessionIndex"] = string.Empty;
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(cookie);

            // End the session
            Session["AppUser"] = null;

            try
            {
                IdpLogoutResponse idpLogoutResponse = SamlHelper.GetLogoutResponse(formCollection["SAMLResponse"].ToString());

                if (!idpLogoutResponse.IsSuccessful)
                {
                    log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP riporta il seguente StatusCode: {idpLogoutResponse.StatusCodeInnerValue} con StatusMessage: {idpLogoutResponse.StatusMessage} e StatusDetail: {idpLogoutResponse.StatusDetail}.");
                    ViewData["Message"]      = "La richiesta di logout è stata rifiutata.";
                    ViewData["ErrorMessage"] = $"StatusCode: {idpLogoutResponse.StatusCodeInnerValue} con StatusMessage: {idpLogoutResponse.StatusMessage} e StatusDetail: {idpLogoutResponse.StatusDetail}.";
                    return(View("Error"));
                }

                // Verifica la corrispondenza del valore di spidLogoutRequestId ricavato da cookie con quello restituito dalla risposta
                if (!SamlHelper.ValidLogoutResponse(idpLogoutResponse, spidLogoutRequestId))
                {
                    log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP non è valida (InResponseTo != spidLogoutRequestId).");
                    ViewData["Message"]      = "La risposta dell'IdP non è valida perché non corrisponde alla richiesta.";
                    ViewData["ErrorMessage"] = $"RequestId: _{spidLogoutRequestId}, RequestPath: {Request.Url.ToString()}, InResponseTo: {idpLogoutResponse.InResponseTo}.";
                    return(View("Error"));
                }

                return(View("Logout"));
            }

            catch (Exception ex)
            {
                log.Error("Error on ACSController [HttpPost]Index method", ex);
                ViewData["Message"]      = "Errore nella lettura della risposta ricevuta dal provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
Example #16
0
        public void SamlRequestTest()
        {
            XmlDocument xmlDoc = SamlHelper.GetSignedRequestDoc("www.Kenexa.com", string.Empty);

            Console.WriteLine(xmlDoc.OuterXml);
        }
        public ActionResult Signin(Models.IdPOptionsModel options)
        {
            string requestId            = Session["requestId"].ToString();
            string requestVersion       = Session["requestVersion"].ToString();
            string requestIssuesInstant = Session["requestIssueInstant"].ToString();
            string requestIssuer        = Session["requestIssuer"].ToString();
            string nameIdPolicyFormat   = Session["nameIdPolicyFormat"].ToString();
            string RelayState           = Session["RelayState"].ToString();
            string username             = Session["username"].ToString();
            int    spId = Convert.ToInt32(Session["spId"]);


            SigningHelper.SignatureType signatureType = SigningHelper.SignatureType.Response;
            if (options.SignAssertion)
            {
                signatureType = SigningHelper.SignatureType.Assertion;
            }

            string strRecipient = Properties.Settings.Default.Recipient;
            string strIssuer    = Properties.Settings.Default.Issuer;
            string strSubject   = username;
            string strAudience  = requestIssuer;

            // Set Parameters to the method call to either the configuration value or a default value
            StoreLocation storeLocation    = StoreLocation.CurrentUser;
            StoreName     storeName        = StoreName.My;
            X509FindType  findType         = X509FindType.FindByThumbprint;
            string        certFileLocation = "";
            string        certPassword     = Properties.Settings.Default.CertPassword;
            string        certFindKey      = Properties.Settings.Default.CertThumbprint;

            Dictionary <string, string> attributes = new Dictionary <string, string>();

            attributes.Add("IDPEmail", username);
            string stringSamlResponse = "";

            try
            {
                stringSamlResponse = SamlHelper.GetPostSamlResponse(strRecipient,
                                                                    strIssuer, strSubject, strAudience, requestId, nameIdPolicyFormat,
                                                                    storeLocation, storeName, findType,
                                                                    certFileLocation, certPassword, certFindKey,
                                                                    attributes, signatureType, options);
                if (options.UrlEncodeSamlResponse)
                {
                    stringSamlResponse = System.Web.HttpUtility.UrlEncode(stringSamlResponse);
                }
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.ToString();
            }
            Logger.DebugFormat(
                "PostData = {0}", stringSamlResponse);


            //
            var model = new Models.SAMLResponseModel();

            model.SAMLResponse = stringSamlResponse;
            if (options.EchoRelayState)
            {
                if (options.UrlEncodeRelayState)
                {
                    model.RelayState = System.Web.HttpUtility.UrlEncode(RelayState);
                }
                else
                {
                    model.RelayState = RelayState;
                }
            }
            else
            {
                //send hardcoded value back
                model.RelayState = "idp.technicality.online";
                if (options.UrlEncodeRelayState)
                {
                    model.RelayState = System.Web.HttpUtility.UrlEncode(model.RelayState);
                }
            }

            if (spId == 1)
            {
                // return to TestSP URL
                model.Destination = Properties.Settings.Default.TestSPUrl;
            }
            else
            {
                model.Destination = strRecipient;
            }

            if (options.SetHeaderToUrlEncoded)
            {
                model.Enctype = "application/x-www-form-urlencoded";
            }
            else
            {
                model.Enctype = "multipart/form-data";
            }
            ViewData.Model = model;

            return(View("SamlResponse"));
        }
Example #18
0
        public ActionResult LogoutRequest()
        {
            string idpName;
            string subjectNameId;
            string authnStatementSessionIndex;

            // Try to get Authentication data from cookie
            HttpCookie cookie = Request.Cookies[SPID_COOKIE];

            if (cookie == null)
            {
                // End the session
                Session["AppUser"] = null;

                log.Error("Error on HomeController LogoutRequest method: Impossibile recuperare i dati della sessione (cookie scaduto)");
                ViewData["Message"] = "Impossibile recuperare i dati della sessione (cookie scaduto).";
                return(View("Error"));
            }

            idpName       = cookie["IdPName"];
            subjectNameId = cookie["SubjectNameId"];
            authnStatementSessionIndex = cookie["AuthnStatementSessionIndex"];

            // Remove the cookie
            cookie.Values["IdPName"]                    = string.Empty;
            cookie.Values["SpidAuthnRequestId"]         = string.Empty;
            cookie.Values["SpidLogoutRequestId"]        = string.Empty;
            cookie.Values["SubjectNameId"]              = string.Empty;
            cookie.Values["AuthnStatementSessionIndex"] = string.Empty;
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(cookie);

            // End the session
            Session["AppUser"] = null;

            if (string.IsNullOrWhiteSpace(idpName) ||
                string.IsNullOrWhiteSpace(subjectNameId) ||
                string.IsNullOrWhiteSpace(authnStatementSessionIndex))
            {
                log.Error("Error on HomeController LogoutRequest method: Impossibile recuperare i dati della sessione (il cookie non contiene tutti i dati necessari)");
                ViewData["Message"] = "Impossibile recuperare i dati della sessione (il cookie non contiene tutti i dati necessari).";
                return(View("Error"));
            }

            try
            {
                // Create the SPID request id and save it as a cookie
                string logoutRequestId = Guid.NewGuid().ToString();

                // Select the Identity Provider
                IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName);

                // Retrieve the signing certificate
                var certificate = X509Helper.GetCertificateFromStore(
                    StoreLocation.LocalMachine, StoreName.My,
                    X509FindType.FindBySubjectName,
                    ConfigurationManager.AppSettings["SPID_CERTIFICATE_NAME"],
                    validOnly: false);

                // Create the signed SAML logout request
                var spidLogoutRequest = SamlHelper.BuildLogoutPostRequest(
                    uuid: logoutRequestId,
                    consumerServiceURL: ConfigurationManager.AppSettings["SPID_DOMAIN_VALUE"],
                    certificate: certificate,
                    identityProvider: idp,
                    subjectNameId: subjectNameId,
                    authnStatementSessionIndex: authnStatementSessionIndex);

                ViewData["data"]   = spidLogoutRequest;
                ViewData["action"] = idp.SingleLogoutServiceUrl;

                // Save the IdP label and SPID request id as a cookie
                cookie = new HttpCookie(SPID_COOKIE);
                cookie.Values["IdPName"]             = idpName;
                cookie.Values["SpidLogoutRequestId"] = logoutRequestId;
                cookie.Expires = DateTime.Now.AddMinutes(20);
                Response.Cookies.Add(cookie);

                // Send the request to the Identity Provider
                return(View("PostData"));
            }
            catch (Exception ex)
            {
                log.Error("Error on HomeController SpidRequest", ex);
                ViewData["Message"]      = "Errore nella preparazione della richiesta di logout da inviare al provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
Example #19
0
        public static string getSamlResponse(string issuerId, X509Certificate2 certificate, string consumerKey, string subject)
        {
            string requestDataEncoded = SamlHelper.Encode64(SamlHelper.CreateSamlAssertion(issuerId, issuerId, subject, certificate));

            return(FixedSamlUtils.PostSamlAssertion(consumerKey, requestDataEncoded));
        }
Example #20
0
        public ActionResult Index(FormCollection formCollection)
        {
            string IdPName;
            string spidAuthnRequestId;

            // Try to get auth requesta data from cookie
            HttpCookie cookie = Request.Cookies[SPID_COOKIE];

            if (cookie != null)
            {
                IdPName            = cookie["IdPName"];
                spidAuthnRequestId = cookie["SpidAuthnRequestId"];
                log.Info($"Cookie {SPID_COOKIE} IdPName: {IdPName}, SpidAuthnRequestId: {spidAuthnRequestId}");
            }
            else
            {
                log.Error("Error on ACSController [HttpPost]Index method: Impossibile recuperare l'Id della sessione.");
                ViewData["Message"] = "Impossibile recuperare i dati della sessione (cookie scaduto).";
                return(View("Error"));
            }

            try
            {
                IdpAuthnResponse idpAuthnResponse = SamlHelper.GetAuthnResponse(formCollection["SAMLResponse"].ToString());

                if (!idpAuthnResponse.IsSuccessful)
                {
                    Session["AppUser"] = null;

                    log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP riporta il seguente StatusCode: {idpAuthnResponse.StatusCodeInnerValue} con StatusMessage: {idpAuthnResponse.StatusMessage} e StatusDetail: {idpAuthnResponse.StatusDetail}.");
                    ViewData["Message"]      = "La richiesta di identificazione è stata rifiutata.";
                    ViewData["ErrorMessage"] = $"StatusCode: {idpAuthnResponse.StatusCodeInnerValue} con StatusMessage: {idpAuthnResponse.StatusMessage} e StatusDetail: {idpAuthnResponse.StatusDetail}.";
                    return(View("Error"));
                }

                // Verifica la corrispondenza del valore di spidAuthnRequestId ricavato da cookie con quello restituito dalla risposta
                if (!SamlHelper.ValidAuthnResponse(idpAuthnResponse, spidAuthnRequestId, Request.Url.ToString()))
                {
                    Session["AppUser"] = null;

                    log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP non è valida (InResponseTo != spidAuthnRequestId oppure SubjectConfirmationDataRecipient != requestPath).");
                    ViewData["Message"]      = "La risposta dell'IdP non è valida perché non corrisponde alla richiesta.";
                    ViewData["ErrorMessage"] = $"RequestId: _{spidAuthnRequestId}, RequestPath: {Request.Url.ToString()}, InResponseTo: {idpAuthnResponse.InResponseTo}, Recipient: {idpAuthnResponse.SubjectConfirmationDataRecipient}.";
                    return(View("Error"));
                }

                // Save request and response data needed to eventually logout as a cookie
                cookie.Values["IdPName"]                    = IdPName;
                cookie.Values["SpidAuthnRequestId"]         = spidAuthnRequestId;
                cookie.Values["SubjectNameId"]              = idpAuthnResponse.SubjectNameId;
                cookie.Values["AuthnStatementSessionIndex"] = idpAuthnResponse.AuthnStatementSessionIndex;
                cookie.Expires = DateTime.Now.AddMinutes(20);
                Response.Cookies.Add(cookie);

                AppUser appUser = new AppUser
                {
                    Name         = SpidUserInfoHelper.Name(idpAuthnResponse.SpidUserInfo),
                    Surname      = SpidUserInfoHelper.FamilyName(idpAuthnResponse.SpidUserInfo),
                    FiscalNumber = SpidUserInfoHelper.FiscalNumber(idpAuthnResponse.SpidUserInfo),
                    Email        = SpidUserInfoHelper.Email(idpAuthnResponse.SpidUserInfo)
                };

                Session.Add("AppUser", appUser);

                ViewData["UserInfo"] = idpAuthnResponse.SpidUserInfo;
                return(View("UserData"));
            }

            catch (Exception ex)
            {
                log.Error("Error on ACSController [HttpPost]Index method", ex);
                ViewData["Message"]      = "Errore nella lettura della risposta ricevuta dal provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
        public ActionResult LogoutRequest()
        {
            // Try to get Authentication data from session
            string idpName       = this.GetCookie("IdPName");
            string subjectNameId = this.GetCookie("SubjectNameId");
            string authnStatementSessionIndex = this.GetCookie("AuthnStatementSessionIndex");

            // End the session
            HttpContext.Session.SetObject <UserInfo>("UserInfo", null);
            this.RemoveCookie("IdPName");
            this.RemoveCookie("SpidAuthnRequestId");
            this.RemoveCookie("SpidLogoutRequestId");
            this.RemoveCookie("SubjectNameId");
            this.RemoveCookie("AuthnStatementSessionIndex");

            if (string.IsNullOrWhiteSpace(idpName) ||
                string.IsNullOrWhiteSpace(subjectNameId) ||
                string.IsNullOrWhiteSpace(authnStatementSessionIndex))
            {
                // TODO: log.Error("Error on HomeController LogoutRequest method: Impossibile recuperare i dati della sessione (sessione scaduta)");
                ViewData["Message"] = "Impossibile recuperare i dati della sessione (sessione scaduta).";
                return(View("Error"));
            }

            try
            {
                // Create the SPID request id and save it as a cookie
                string logoutRequestId = Guid.NewGuid().ToString();

                // Select the Identity Provider
                IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName);

                // Retrieve the signing certificate
                var certificate = X509Helper.GetCertificateFromStore(
                    StoreLocation.LocalMachine, StoreName.My,
                    X509FindType.FindBySubjectName,
                    _configuration["Spid:CertificateName"],
                    validOnly: false);

                // Create the signed SAML logout request
                var spidLogoutRequest = SamlHelper.BuildLogoutPostRequest(
                    uuid: logoutRequestId,
                    consumerServiceURL: _configuration["Spid:DomainValue"],
                    certificate: certificate,
                    identityProvider: idp,
                    subjectNameId: subjectNameId,
                    authnStatementSessionIndex: authnStatementSessionIndex);

                ViewData["data"]   = spidLogoutRequest;
                ViewData["action"] = idp.SingleLogoutServiceUrl;

                // Save the IdP label and SPID logout request id
                this.SetCookie("IdPName", idpName, 20);
                this.SetCookie("SpidLogoutRequestId", logoutRequestId, 20);

                // Send the request to the Identity Provider
                return(View("PostData"));
            }
            catch (Exception ex)
            {
                // TODO: log.Error("Error on HomeController SpidRequest", ex);
                ViewData["Message"]      = "Errore nella preparazione della richiesta di logout da inviare al provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
Example #22
0
        public ActionResult Index(IFormCollection formCollection)
        {
            // Try to get auth requesta data
            string idPName            = this.GetCookie("IdPName");
            string spidAuthnRequestId = this.GetCookie("SpidAuthnRequestId");

            if (string.IsNullOrWhiteSpace(idPName) || string.IsNullOrWhiteSpace(spidAuthnRequestId))
            {
                // TODO: log.Error("Error on ACSController [HttpPost]Index method: Impossibile recuperare l'Id della sessione.");
                ViewData["Message"] = "Impossibile recuperare i dati della sessione (cookie scaduto).";
                return(View("Error"));
            }

            try
            {
                IdpAuthnResponse idpAuthnResponse = SamlHelper.GetAuthnResponse(formCollection["SAMLResponse"].ToString());

                if (!idpAuthnResponse.IsSuccessful)
                {
                    // End the session
                    this.RemoveCookie("IdPName");
                    this.RemoveCookie("SpidAuthnRequestId");
                    this.RemoveCookie("SpidLogoutRequestId");
                    this.RemoveCookie("SubjectNameId");
                    this.RemoveCookie("AuthnStatementSessionIndex");

                    // TODO: log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP riporta il seguente StatusCode: {idpAuthnResponse.StatusCodeInnerValue} con StatusMessage: {idpAuthnResponse.StatusMessage} e StatusDetail: {idpAuthnResponse.StatusDetail}.");
                    ViewData["Message"]      = "La richiesta di identificazione è stata rifiutata.";
                    ViewData["ErrorMessage"] = $"StatusCode: {idpAuthnResponse.StatusCodeInnerValue} con StatusMessage: {idpAuthnResponse.StatusMessage} e StatusDetail: {idpAuthnResponse.StatusDetail}.";
                    return(View("Error"));
                }

                string requestUrl = $"http{(Request.IsHttps ? "s" : "")}://{Request.Host.ToString()}{Request.Path.ToString()}";

                // Verifica la corrispondenza del valore di spidAuthnRequestId ricavato dalla sessione con quello restituito dalla risposta
                if (!SamlHelper.ValidAuthnResponse(idpAuthnResponse, spidAuthnRequestId, requestUrl))
                {
                    // TODO: log.Error($"Error on ACSController [HttpPost]Index method: La risposta dell'IdP non è valida (InResponseTo != spidAuthnRequestId oppure SubjectConfirmationDataRecipient != requestPath).");
                    ViewData["Message"]      = "La risposta dell'IdP non è valida perché non corrisponde alla richiesta.";
                    ViewData["ErrorMessage"] = $"RequestId: _{spidAuthnRequestId}, RequestPath: {requestUrl}, InResponseTo: {idpAuthnResponse.InResponseTo}, Recipient: {idpAuthnResponse.SubjectConfirmationDataRecipient}.";
                    return(View("Error"));
                }

                HttpContext.Session.SetObject <UserInfo>("UserInfo", new UserInfo
                {
                    Name         = SpidUserInfoHelper.Name(idpAuthnResponse.SpidUserInfo),
                    Surname      = SpidUserInfoHelper.FamilyName(idpAuthnResponse.SpidUserInfo),
                    FiscalNumber = SpidUserInfoHelper.FiscalNumber(idpAuthnResponse.SpidUserInfo),
                    Email        = SpidUserInfoHelper.Email(idpAuthnResponse.SpidUserInfo)
                });

                // Save request and response data needed to eventually logout
                this.SetCookie("IdPName", idPName, 20);
                this.SetCookie("SpidAuthnRequestId", spidAuthnRequestId, 20);
                this.SetCookie("SubjectNameId", idpAuthnResponse.SubjectNameId, 20);
                this.SetCookie("AuthnStatementSessionIndex", idpAuthnResponse.AuthnStatementSessionIndex, 20);

                ViewData["UserInfo"] = idpAuthnResponse.SpidUserInfo;
                return(View("UserData"));
            }

            catch (Exception ex)
            {
                // TODO: log.Error("Error on ACSController [HttpPost]Index method", ex);
                ViewData["Message"]      = "Errore nella lettura della risposta ricevuta dal provider.";
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }