public LogoutRequestType Map(SamlRequestOption source) { DateTime requestDateTime = DateTime.UtcNow; LogoutRequestType logoutRequest = new LogoutRequestType() { ID = string.Concat("_", source.Id.ToString()), Version = source.Version, IssueInstant = requestDateTime, Destination = source.Destination, Issuer = new NameIDType { Format = SamlNamespaceHelper.SAML_ENTITY_NAMESPACE, NameQualifier = source.SPDomain, Value = source.SPDomain }, Item = new NameIDType { SPNameQualifier = source.SPDomain, Format = SamlNamespaceHelper.SAML_TRANSIENT_NAMESPACE, Value = source.SubjectNameId }, NotOnOrAfterSpecified = true, NotOnOrAfter = requestDateTime.Add(source.NotOnOrAfter), Reason = SamlNamespaceHelper.SAML_LOGOUT_USER_NAMESPACE, SessionIndex = new string[] { source.AuthnStatementSessionIndex } }; return(logoutRequest); }
public IActionResult Auth(string idp) { return(ActionHelper.TryCatchWithLoggerGeneric <IActionResult>(() => { if (string.IsNullOrEmpty(idp)) { throw new ArgumentNullException(nameof(idp), "Auth -> parameter idp is null"); } string idpUrl = _idpHelper.GetSingleSignOnUrl(idp); if (string.IsNullOrEmpty(idpUrl)) { throw new Exception(string.Concat("Auth -> idp url not found for idp ", idpUrl)); } SamlRequestOption samlRequestOption = _requestOptionFactory.GenerateAuthRequestOption(idp); if (samlRequestOption == null) { throw new Exception("Auth -> error on generate saml model option"); } string samlrequest = _authRequest.PostableAuthRequest(samlRequestOption, _spidConfiguration.CertificatePrivateKey); ClearCookies(); this.SetCookie("SpidAuthnRequestId", samlRequestOption.Id.ToString(), 20); ViewData["SAMLRequest"] = samlrequest; ViewData["FormUrlAction"] = idpUrl; ViewData["RelayState"] = Guid.NewGuid(); return View(); }, _logger)); }
public string PostableLogOutRequest(SamlRequestOption requestOption, string xmlPrivateKey = "") { try { _logger.LogInformation("PostableLogOutRequest -> initialize logout request for IDP {0}", requestOption.Destination); LogoutRequestType logOutRequest = _logOutRequestTypeMapper.Map(requestOption); _logger.LogInformation("PostableLogOutRequest -> request created with id {0}", logOutRequest.ID); XmlDocument xmlRequest = new XmlDocument(); xmlRequest.LoadXml(logOutRequest.ToXmlString()); _logger.LogInformation("PostableLogOutRequest -> generating signature for id {0}...", logOutRequest.ID); XmlElement signatureElement = _signatureHelper.GetXmlAuthRequestSignature(xmlRequest, requestOption.Certificate, xmlPrivateKey); xmlRequest.DocumentElement.InsertAfter(signatureElement, xmlRequest.DocumentElement.ChildNodes[0]); _logger.LogInformation("PostableLogOutRequest -> signature generated correctly"); _logger.LogDebug("PostableLogOutRequest -> request id {0} - xml: {1}", logOutRequest.ID, xmlRequest.OuterXml); _traceLogger.LogInformation("LogoutReq_ID: {0}|LogouteReq_IssueInstant: {1}|LogouteReq_SAML: {2}", logOutRequest.ID, logOutRequest.IssueInstant, xmlRequest.OuterXml); return(Convert.ToBase64String(Encoding.UTF8.GetBytes(xmlRequest.OuterXml))); } catch (Exception ex) { _logger.LogError(ex, "PostableLogOutRequest -> error on creating postable logout request"); throw; } }
public string RedirectableAuthRequest(SamlRequestOption requestOption, string xmlPrivateKey = "") { try { _logger.LogInformation("RedirectableAuthRequest -> initialize request for IDP {0}", requestOption.Destination); AuthnRequestType authnRequest = _authRequestTypeMapper.Map(requestOption); authnRequest.ProtocolBinding = SamlNamespaceHelper.SAML_PROTOCOL_BINDING_REDIRECT_NAMESPACE; _logger.LogInformation("RedirectableAuthRequest -> request created with id {0}", authnRequest.ID); string compressedRequest = WebUtility.UrlEncode(CompressRequest(authnRequest)); string sigAlg = WebUtility.UrlEncode(SignatureHelper.SIGNATURE_ALGORITHM_SHA256); _logger.LogInformation("RedirectableAuthRequest -> generating signature for id {0}...", authnRequest.ID); string tmpRequest = string.Concat("SAMLRequest=", compressedRequest, "&SigAlg=", sigAlg); string requestSignature = _signatureHelper.SignMessage(tmpRequest, requestOption.Certificate, xmlPrivateKey); _logger.LogInformation("RedirectableAuthRequest -> signature generated correctly"); string requestQueryString = string.Concat(tmpRequest, "&Signature=", requestSignature); _logger.LogDebug("RedirectableAuthRequest -> request id {0} - query string: {1}", authnRequest.ID, requestQueryString); _traceLogger.LogInformation("AuthnReq_ID: {0}|AuthnReq_IssueInstant: {1}|AuthnReq_QS: {2}", authnRequest.ID, authnRequest.IssueInstant, requestQueryString); return(requestQueryString); } catch (Exception ex) { _logger.LogError(ex, "RedirectableAuthRequest -> error on creating redirectable auth request"); throw; } }
public IActionResult LogOut(string ReferenceCode, string IdpName) { return(ActionHelper.TryCatchWithLoggerGeneric <IActionResult>(() => { if (string.IsNullOrEmpty(ReferenceCode)) { _logger.LogWarning("LogOut -> parameter reference code is null"); return BadRequest(); } string idpUrl = _idpHelper.GetSingleLogoutUrl(IdpName); if (string.IsNullOrEmpty(idpUrl)) { throw new Exception(string.Concat("Auth -> idp url not found for idp ", idpUrl)); } string token = _tokenService.Find(_dataProtectionService.Unprotect(ReferenceCode)); string idpReferenceId = string.Empty; if (!string.IsNullOrEmpty(token)) { JwtSecurityToken jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token); idpReferenceId = jwtToken.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.NameId)?.Value; } _tokenService.Remove(ReferenceCode); _sessionAuthLogger.LogInformation("Disconnessione effettuata correttamente dall' utente {0}", idpReferenceId); ViewData["FormUrlAction"] = idpUrl; if (_spidConfiguration.IdpType == Model.IDP.IdpType.FedERa) { ViewData["SPID"] = _spidConfiguration.SPDomain; ViewData["SPURL"] = _spidConfiguration.LogoutCallback; _traceLogger.LogInformation("LogoutReq_SPID: {0}|LogoutReq_SPURL: {1}", _spidConfiguration.SPDomain, _spidConfiguration.LogoutCallback); return View("LogOutFedera"); } SamlRequestOption samlRequestOption = _requestOptionFactory.GenerateLogoutRequestOption(IdpName); if (samlRequestOption == null) { throw new Exception("Auth -> error on generate saml model option"); } string samlrequest = _authRequest.PostableLogOutRequest(samlRequestOption, _spidConfiguration.CertificatePrivateKey); ClearCookies(); this.SetCookie("SpidLogoutRequestId", samlRequestOption.Id.ToString(), 20); ViewData["RelayState"] = Guid.NewGuid(); ViewData["SAMLRequest"] = samlrequest; return View("LogOutSPID"); }, _logger)); }
public AuthnRequestType Map(SamlRequestOption source) { DateTime requestDateTime = DateTime.UtcNow; return(new AuthnRequestType() { ID = string.Concat("_", source.Id.ToString()), Version = source.Version, IssueInstant = requestDateTime, Destination = source.Destination, AttributeConsumingServiceIndex = source.AttributeConsumingServiceIndex ?? 0, AttributeConsumingServiceIndexSpecified = source.AttributeConsumingServiceIndex.HasValue, ForceAuthnSpecified = true, ForceAuthn = source.SPIDLevel != SamlAuthLevel.SpidL1, AssertionConsumerServiceIndex = source.AssertionConsumerServiceIndex, AssertionConsumerServiceIndexSpecified = true, Issuer = new NameIDType() { Format = SamlNamespaceHelper.SAML_ENTITY_NAMESPACE, NameQualifier = source.SPDomain, Value = source.SPDomain }, NameIDPolicy = new NameIDPolicyType() { Format = SamlNamespaceHelper.SAML_TRANSIENT_NAMESPACE, AllowCreate = true }, Conditions = new ConditionsType() { NotBefore = requestDateTime.Add(source.NotBefore), NotBeforeSpecified = true, NotOnOrAfter = requestDateTime.Add(source.NotOnOrAfter), NotOnOrAfterSpecified = true }, RequestedAuthnContext = new RequestedAuthnContextType() { Comparison = AuthnContextComparisonType.minimum, ComparisonSpecified = true, ItemsElementName = new ItemsChoiceType7[] { ItemsChoiceType7.AuthnContextClassRef }, Items = new string[] { AuthContextSecurityLevel(source.SPIDLevel) } } }); }
public void CreateRedirectRequestAndCheckResultNotEmpty() { using (X509Certificate2 cert = new X509Certificate2("spid-developer.pfx", "Passw0rd", X509KeyStorageFlags.Exportable)) { SamlRequestOption options = new SamlRequestOption() { SPIDLevel = SamlAuthLevel.SpidL1, SPDomain = "http://www.vecompsoftware.it", Destination = "http://idp.test.it", AssertionConsumerServiceIndex = 1, AttributeConsumingServiceIndex = 1, Certificate = cert }; NullLoggerFactory log = new NullLoggerFactory(); NullLoggerFactory logHelper = new NullLoggerFactory(); //AuthRequest request = new AuthRequest(log, new SignatureHelper(logHelper)); //string result = request.RedirectableSpidAuthRequest(options); //Assert.AreNotEqual(string.Empty, request); } }
private SamlRequestOption GenerateRequestOption(string idp, string destinationUrl) { X509Certificate2 certificate = GetCertificate(); if (certificate == null) { _logger.LogWarning("Nessun certificato trovato per la configurazione passata"); return(null); } SamlRequestOption samlRequestOption = new SamlRequestOption() { SPIDLevel = (SamlAuthLevel)_spidConfiguration.IdpAuthLevel, SPDomain = _spidConfiguration.SPDomain, AssertionConsumerServiceIndex = (ushort)_spidConfiguration.AssertionConsumerServiceIndex, AttributeConsumingServiceIndex = (ushort?)_spidConfiguration.AttributeConsumingServiceIndex, Destination = destinationUrl, Certificate = certificate, IdpEntityId = _idpHelper.GetEntityId(idp) }; return(samlRequestOption); }