//public ActionResult Login(string returnUrl)
        //{
        //    var binding = new Saml2RedirectBinding();
        //    binding.SetRelayStateQuery(new Dictionary<string, string> { { relayStateReturnUrl, returnUrl } });

        //    return binding.Bind(new Saml2AuthnRequest
        //    {
        //        //ForceAuthn = true,
        //        //NameIdPolicy = new NameIdPolicy { AllowCreate = true, Format = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" },
        //        RequestedAuthnContext = new RequestedAuthnContext
        //        {
        //            Comparison = AuthnContextComparisonTypes.Exact,
        //            AuthnContextClassRef = new string[] { AuthnContextClassTypes.PasswordProtectedTransport.OriginalString },
        //        },
        //        Issuer = new EndpointReference("http://udv.itfoxtec.com/webapptest"),
        //        Destination = new EndpointAddress("https://udv.itfoxtec.com/adfs/ls/"),
        //        AssertionConsumerServiceUrl = new EndpointAddress("https://udv.itfoxtec.com/webapptest/Auth/AssertionConsumerService")
        //    }).ToActionResult();
        //}

        //public ActionResult Login(string returnUrl)
        //{
        //    var binding = new Saml2RedirectBinding();
        //    binding.SetRelayStateQuery(new Dictionary<string, string> { { relayStateReturnUrl, returnUrl } });

        //    return binding.Bind(new Saml2AuthnRequest
        //    {
        //        //ForceAuthn = true,
        //        //NameIdPolicy = new NameIdPolicy { AllowCreate = true, Format = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" },
        //        RequestedAuthnContext = new RequestedAuthnContext
        //        {
        //            Comparison = AuthnContextComparisonTypes.Exact,
        //            AuthnContextClassRef = new string[] { AuthnContextClassTypes.PasswordProtectedTransport.OriginalString },
        //        },
        //        Issuer = new EndpointReference("http://udv.itfoxtec.com/webapptest"),
        //        Destination = new EndpointAddress("https://sso.connect.pingidentity.com/sso/idp/SSO.saml2?idpid=77812690-a6a2-42f7-968c-98d4b07a880f"),
        //        AssertionConsumerServiceUrl = new EndpointAddress("https://sso.connect.pingidentity.com/sso/idp/SSO.saml2?idpid=77812690-a6a2-42f7-968c-98d4b07a880f")
        //    }).ToActionResult();
        //}

        //public ActionResult AssertionConsumerService()
        //{
        //    var binding = new Saml2PostBinding();
        //    var saml2AuthnResponse = new Saml2AuthnResponse();

        //    binding.Unbind(Request, saml2AuthnResponse, CertificateUtil.Load("~/App_Data/signing-adfs.test_Certificate.crt"));
        //    saml2AuthnResponse.CreateSession();

        //    var returnUrl = binding.GetRelayStateQuery()[relayStateReturnUrl];
        //    return Redirect(string.IsNullOrWhiteSpace(returnUrl) ? Url.Content("~/") : returnUrl);
        //}

        public ActionResult Login()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse();

            //binding.Unbind(Request, saml2AuthnResponse, CertificateUtil.Load("~/App_Data/signing-adfs.test_Certificate.crt"));
            binding.Unbind(Request, saml2AuthnResponse, CertificateUtil.Load("~/App_Data/idp-signing.crt"));
            //saml2AuthnResponse.CreateSession();

            Saml2StatusCodes testcode = saml2AuthnResponse.Status;

            string UserName = "";

            foreach (Claim claim in saml2AuthnResponse.ClaimsIdentity.Claims)
            {
                //string test = claim.Value;
                //test = claim.ValueType;
                //test = claim.Type;
                //       ClaimsIdentity test1 = claim.Subject;
                //       Claim test2 = claim.Subject.FindFirst("Email");
                if (claim.Type == "Email")
                {
                    UserName = claim.Value;
                }
            }



            bool testAuth = User.Identity.IsAuthenticated;

            FormsAuthentication.SetAuthCookie(UserName, true);

            //if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            //{
            //    return RedirectToLocal(returnUrl);
            //}

            //// If we got this far, something failed, redisplay form
            //ModelState.AddModelError("", "The user name or password provided is incorrect.");
            //return View(model);

            //var returnUrl = binding.GetRelayStateQuery()[relayStateReturnUrl];
            //return Redirect(string.IsNullOrWhiteSpace(returnUrl) ? Url.Content("~/") : returnUrl);
            return(Redirect("~/Home/Index"));
        }
示例#2
0
        public async Task <IActionResult> LogoutResponseAsync(string partyId, Saml2StatusCodes status = Saml2StatusCodes.Success, string sessionIndex = null)
        {
            logger.ScopeTrace($"Down, SAML Logout response{(status != Saml2StatusCodes.Success ? " error" : string.Empty )}, Status code '{status}'.");
            logger.SetScopeProperty("downPartyId", partyId);

            var party = await tenantRepository.GetAsync <SamlDownParty>(partyId);

            ValidatePartyLogoutSupport(party);

            var samlConfig = saml2ConfigurationLogic.GetSamlDownConfig(party, true);

            var sequenceData = await sequenceLogic.GetSequenceDataAsync <SamlDownSequenceData>(false);

            logger.ScopeTrace($"Binding '{party.LogoutBinding.ResponseBinding}'");
            switch (party.LogoutBinding.ResponseBinding)
            {
            case SamlBindingType.Redirect:
                return(await LogoutResponseAsync(samlConfig, sequenceData.Id, sequenceData.RelayState, sequenceData.ResponseUrl, new Saml2RedirectBinding(), status, sessionIndex));

            case SamlBindingType.Post:
                return(await LogoutResponseAsync(samlConfig, sequenceData.Id, sequenceData.RelayState, sequenceData.ResponseUrl, new Saml2PostBinding(), status, sessionIndex));

            default:
                throw new NotSupportedException($"SAML binding '{party.LogoutBinding.ResponseBinding}' not supported.");
            }
        }
示例#3
0
        private IActionResult LoginResponse(Saml2Id inResponseTo, Saml2StatusCodes status, string relayState, RelyingParty relyingParty, string sessionIndex = null, IEnumerable <Claim> claims = null)
        {
            var responsebinding = new Saml2PostBinding();

            responsebinding.RelayState = relayState;

            var saml2AuthnResponse = new Saml2AuthnResponse(GetLoginSaml2Config(relyingParty))
            {
                InResponseTo = inResponseTo,
                Status       = status,
                Destination  = relyingParty.SingleSignOnDestination,
            };

            if (status == Saml2StatusCodes.Success && claims != null)
            {
                saml2AuthnResponse.SessionIndex = sessionIndex;

                var claimsIdentity = new ClaimsIdentity(claims);
                saml2AuthnResponse.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent);
                //saml2AuthnResponse.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single());
                saml2AuthnResponse.ClaimsIdentity = claimsIdentity;

                _ = saml2AuthnResponse.CreateSecurityToken(relyingParty.Issuer);
            }

            return(responsebinding.Bind(saml2AuthnResponse).ToActionResult());
        }
示例#4
0
        private IActionResult LoginResponse(Saml2Id inResponseTo, Saml2StatusCodes status, string relayState, App app, string sessionIndex = null, IEnumerable <Claim> claims = null)
        {
            var responseBinding = new Saml2PostBinding();

            responseBinding.RelayState = relayState;

            var saml2AuthnResponse = new Saml2AuthnResponse(_samlConfig)
            {
                InResponseTo = inResponseTo,
                Status       = status,
                Destination  = app.SingleSignOnDestination
            };

            if (status == Saml2StatusCodes.Success && claims != null)
            {
                saml2AuthnResponse.SessionIndex = sessionIndex;

                var claimsIdentity = new ClaimsIdentity(claims);
                saml2AuthnResponse.NameId         = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent);
                saml2AuthnResponse.ClaimsIdentity = claimsIdentity;

                saml2AuthnResponse.CreateSecurityToken(app.Issuer, subjectConfirmationLifetime: 5, issuedTokenLifetime: 60);
            }

            return(responseBinding.Bind(saml2AuthnResponse).ToActionResult());
        }
        private ActionResult LoginResponse(Saml2AuthnRequest saml2AuthnRequest, Saml2StatusCodes status, string relayState, RelyingParty relyingParty, string sessionIndex = null, IEnumerable <Claim> claims = null)
        {
            var responsebinding = new Saml2RedirectBinding();

            responsebinding.RelayState = relayState;

            var saml2AuthnResponse = new Saml2AuthnResponse(config)
            {
                InResponseTo = saml2AuthnRequest.Id,
                Status       = status,
                Destination  = relyingParty.SingleSignOnDestination,
                Extensions   = saml2AuthnRequest.Extensions
            };

            if (status == Saml2StatusCodes.Success && claims != null)
            {
                saml2AuthnResponse.SessionIndex = sessionIndex;

                var claimsIdentity = new ClaimsIdentity(claims);
                saml2AuthnResponse.NameId         = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent);
                saml2AuthnResponse.ClaimsIdentity = claimsIdentity;

                var token = saml2AuthnResponse.CreateSecurityToken(SettingManager.GetInstance().Configuration.Issuer);
            }

            return(responsebinding.Bind(saml2AuthnResponse).ToActionResult());
        }
示例#6
0
        internal override void Read(string xml, bool validateXmlSignature = false)
        {
            base.Read(xml, validateXmlSignature);

            Status = Saml2StatusCodeUtil.ToEnum(XmlDocument.DocumentElement[Saml2Constants.Message.Status, Saml2Constants.ProtocolNamespace.OriginalString][Saml2Constants.Message.StatusCode, Saml2Constants.ProtocolNamespace.OriginalString].Attributes[Saml2Constants.Message.Value].GetValueOrNull());

            DecryptMessage();

            if (validateXmlSignature)
            {
                ValidateXmlSignature();
            }
        }
示例#7
0
        public async Task <IActionResult> LogoutResponseAsync(string partyId, Saml2StatusCodes status = Saml2StatusCodes.Success, string sessionIndex = null)
        {
            logger.SetScopeProperty("downPartyId", partyId);

            var party = await tenantRepository.GetAsync <SamlDownParty>(partyId);

            ValidatePartyLogoutSupport(party);

            var samlConfig   = saml2ConfigurationLogic.GetSamlDownConfig(party, true);
            var sequenceData = await sequenceLogic.GetSequenceDataAsync <SamlDownSequenceData>(false);

            return(await LogoutResponseAsync(party, samlConfig, sequenceData.Id, sequenceData.RelayState, status, sessionIndex));
        }
示例#8
0
        private string StatusToOAuth2OidcError(Saml2StatusCodes status)
        {
            switch (status)
            {
            case Saml2StatusCodes.AuthnFailed:
            case Saml2StatusCodes.NoAuthnContext:
            case Saml2StatusCodes.NoPassive:
                return(IdentityConstants.ResponseErrors.LoginRequired);

            default:
                return(IdentityConstants.ResponseErrors.InvalidRequest);
            }
        }
示例#9
0
        internal override void Read(string xml, bool validateXmlSignature = false)
        {
            base.Read(xml, validateXmlSignature);

            Status = Saml2StatusCodeUtil.ToEnum(XmlDocument.DocumentElement[Saml2Constants.Message.Status, Saml2Constants.ProtocolNamespace.OriginalString][Saml2Constants.Message.StatusCode, Saml2Constants.ProtocolNamespace.OriginalString].Attributes[Saml2Constants.Message.Value].GetValueOrNull());

            DecryptMessage();

            if (validateXmlSignature)
            {
                ValidateXmlSignature();
            }
        }
示例#10
0
        public async Task <IActionResult> AuthnResponseAsync(string partyId, Saml2StatusCodes status = Saml2StatusCodes.Success, IEnumerable <Claim> jwtClaims = null)
        {
            logger.ScopeTrace($"Down, SAML Authn response{(status != Saml2StatusCodes.Success ? " error" : string.Empty )}, Status code '{status}'.");
            logger.SetScopeProperty("downPartyId", partyId);

            var party = await tenantRepository.GetAsync <SamlDownParty>(partyId);

            var samlConfig   = saml2ConfigurationLogic.GetSamlDownConfig(party, true);
            var sequenceData = await sequenceLogic.GetSequenceDataAsync <SamlDownSequenceData>(false);

            var claims = jwtClaims != null ? await claimsDownLogic.FromJwtToSamlClaimsAsync(jwtClaims) : null;

            return(await AuthnResponseAsync(party, samlConfig, sequenceData.Id, sequenceData.RelayState, sequenceData.AcsResponseUrl, status, claims));
        }
示例#11
0
        private IActionResult LogoutResponse(Saml2Id inResponseTo, Saml2StatusCodes status, string relayState, string sessionIndex, RelyingParty relyingParty)
        {
            var responsebinding = new Saml2PostBinding();

            responsebinding.RelayState = relayState;

            var saml2LogoutResponse = new Saml2LogoutResponse(saml2Config)
            {
                InResponseTo = inResponseTo,
                Status       = status,
                Destination  = relyingParty.SingleLogoutResponseDestination,
                SessionIndex = sessionIndex
            };

            return(responsebinding.Bind(saml2LogoutResponse).ToActionResult());
        }
示例#12
0
        private async Task <IActionResult> AuthnResponseDownAsync(SamlUpSequenceData sequenceData, Saml2StatusCodes status, IEnumerable <Claim> claims = null)
        {
            logger.ScopeTrace($"Response, Down type {sequenceData.DownPartyType}.");
            switch (sequenceData.DownPartyType)
            {
            case PartyTypes.OAuth2:
                throw new NotImplementedException();

            case PartyTypes.Oidc:
                if (status == Saml2StatusCodes.Success)
                {
                    var claimsLogic = serviceProvider.GetService <ClaimsLogic <OidcDownClient, OidcDownScope, OidcDownClaim> >();
                    return(await serviceProvider.GetService <OidcAuthDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().AuthenticationResponseAsync(sequenceData.DownPartyId, await claimsLogic.FromSamlToJwtClaims(claims)));
                }
                else
                {
                    return(await serviceProvider.GetService <OidcAuthDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().AuthenticationResponseErrorAsync(sequenceData.DownPartyId, StatusToOAuth2OidcError(status)));
                }

            case PartyTypes.Saml2:
                return(await serviceProvider.GetService <SamlAuthnDownLogic>().AuthnResponseAsync(sequenceData.DownPartyId, status, claims));

            default:
                throw new NotSupportedException();
            }
        }
示例#13
0
        private async Task <IActionResult> AuthnResponseDownAsync(SamlUpSequenceData sequenceData, Saml2StatusCodes status, List <Claim> jwtClaims = null)
        {
            try
            {
                logger.ScopeTrace(() => $"Response, Down type {sequenceData.DownPartyLink.Type}.");
                switch (sequenceData.DownPartyLink.Type)
                {
                case PartyTypes.OAuth2:
                    throw new NotImplementedException();

                case PartyTypes.Oidc:
                    if (status == Saml2StatusCodes.Success)
                    {
                        return(await serviceProvider.GetService <OidcAuthDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().AuthenticationResponseAsync(sequenceData.DownPartyLink.Id, jwtClaims));
                    }
                    else
                    {
                        return(await serviceProvider.GetService <OidcAuthDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().AuthenticationResponseErrorAsync(sequenceData.DownPartyLink.Id, StatusToOAuth2OidcError(status)));
                    }

                case PartyTypes.Saml2:
                    return(await serviceProvider.GetService <SamlAuthnDownLogic>().AuthnResponseAsync(sequenceData.DownPartyLink.Id, status, jwtClaims));

                default:
                    throw new NotSupportedException();
                }
            }
            catch (Exception ex)
            {
                throw new StopSequenceException("Falling authn response down", ex);
            }
        }
示例#14
0
        private async Task <IActionResult> LogoutResponseAsync <T>(Saml2Configuration samlConfig, string inResponseTo, string relayState, string singleLogoutResponseUrl, Saml2Binding <T> binding, Saml2StatusCodes status, string sessionIndex)
        {
            binding.RelayState = relayState;

            var saml2LogoutResponse = new Saml2LogoutResponse(samlConfig)
            {
                InResponseTo = new Saml2Id(inResponseTo),
                Status       = status,
                Destination  = new Uri(singleLogoutResponseUrl),
                SessionIndex = sessionIndex
            };

            binding.Bind(saml2LogoutResponse);
            logger.ScopeTrace(() => $"SAML Single Logout response '{saml2LogoutResponse.XmlDocument.OuterXml}'.", traceType: TraceTypes.Message);
            logger.ScopeTrace(() => $"Single logged out response URL '{singleLogoutResponseUrl}'.");
            logger.ScopeTrace(() => "Down, SAML Single Logout response.", triggerEvent: true);

            await sequenceLogic.RemoveSequenceDataAsync <SamlDownSequenceData>();

            securityHeaderLogic.AddFormActionAllowAll();

            if (binding is Saml2Binding <Saml2RedirectBinding> )
            {
                return(await(binding as Saml2RedirectBinding).ToActionFormResultAsync());
            }
            if (binding is Saml2Binding <Saml2PostBinding> )
            {
                return(await(binding as Saml2PostBinding).ToActionFormResultAsync());
            }
            else
            {
                throw new NotSupportedException();
            }
        }
示例#15
0
        private async Task <IActionResult> SingleLogoutResponseAsync(SamlUpParty party, Saml2Configuration samlConfig, string inResponseTo, string relayState, Saml2StatusCodes status = Saml2StatusCodes.Success, string sessionIndex = null)
        {
            logger.ScopeTrace(() => $"Down, SAML Single Logout response{(status != Saml2StatusCodes.Success ? " error" : string.Empty)}, Status code '{status}'.");

            var binding = party.LogoutBinding.ResponseBinding;

            logger.ScopeTrace(() => $"Binding '{binding}'");
            switch (binding)
            {
            case SamlBindingTypes.Redirect:
                return(await LogoutResponseAsync(samlConfig, inResponseTo, relayState, GetSingleLogoutResponseUrl(party), new Saml2RedirectBinding(), status, sessionIndex));

            case SamlBindingTypes.Post:
                return(await LogoutResponseAsync(samlConfig, inResponseTo, relayState, GetSingleLogoutResponseUrl(party), new Saml2PostBinding(), status, sessionIndex));

            default:
                throw new NotSupportedException($"SAML binding '{binding}' not supported.");
            }
        }
示例#16
0
        private async Task <IActionResult> SingleLogoutResponseAsync(SamlUpSequenceData sequenceData, Saml2StatusCodes status = Saml2StatusCodes.Success, string sessionIndex = null)
        {
            logger.SetScopeProperty(Constants.Logs.UpPartyId, sequenceData.UpPartyId);

            var party = await tenantRepository.GetAsync <SamlUpParty>(sequenceData.UpPartyId);

            ValidatePartyLogoutSupport(party);

            var samlConfig = await saml2ConfigurationLogic.GetSamlUpConfigAsync(party, includeSigningAndDecryptionCertificate : true);

            return(await SingleLogoutResponseAsync(party, samlConfig, sequenceData.Id, sequenceData.RelayState, status, sessionIndex));
        }
示例#17
0
        private async Task <IActionResult> LogoutResponseDownAsync(SamlUpSequenceData sequenceData, Saml2StatusCodes status = Saml2StatusCodes.Success)
        {
            try
            {
                logger.ScopeTrace(() => $"Response, Down type {sequenceData.DownPartyLink.Type}.");
                switch (sequenceData.DownPartyLink.Type)
                {
                case PartyTypes.OAuth2:
                    throw new NotImplementedException();

                case PartyTypes.Oidc:
                    if (status == Saml2StatusCodes.Success)
                    {
                        return(await serviceProvider.GetService <OidcRpInitiatedLogoutDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().EndSessionResponseAsync(sequenceData.DownPartyLink.Id));
                    }
                    else
                    {
                        throw new StopSequenceException($"SAML up Logout failed, Status '{status}', Name '{RouteBinding.UpParty.Name}'.");
                    }

                case PartyTypes.Saml2:
                    return(await serviceProvider.GetService <SamlLogoutDownLogic>().LogoutResponseAsync(sequenceData.DownPartyLink.Id, status, sequenceData.SessionId));

                default:
                    throw new NotSupportedException();
                }
            }
            catch (StopSequenceException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new StopSequenceException("Falling logout response down", ex);
            }
        }
示例#18
0
        private Task <IActionResult> AuthnResponseAsync(SamlDownParty party, Saml2Configuration samlConfig, string inResponseTo, string relayState, string acsUrl, Saml2StatusCodes status, IEnumerable <Claim> claims = null)
        {
            logger.ScopeTrace(() => $"Down, SAML Authn response{(status != Saml2StatusCodes.Success ? " error" : string.Empty)}, Status code '{status}'.");

            var binding = party.AuthnBinding.ResponseBinding;

            logger.ScopeTrace(() => $"Binding '{binding}'");
            switch (binding)
            {
            case SamlBindingTypes.Redirect:
                return(AuthnResponseAsync(party, samlConfig, inResponseTo, relayState, acsUrl, new Saml2RedirectBinding(), status, claims));

            case SamlBindingTypes.Post:
                return(AuthnResponseAsync(party, samlConfig, inResponseTo, relayState, acsUrl, new Saml2PostBinding(), status, claims));

            default:
                throw new NotSupportedException($"SAML binding '{binding}' not supported.");
            }
        }
示例#19
0
        private async Task <IActionResult> LogoutResponseAsync <T>(Saml2Configuration samlConfig, string inResponseTo, string relayState, string loggedOutUrl, Saml2Binding <T> binding, Saml2StatusCodes status, string sessionIndex = null)
        {
            binding.RelayState = relayState;

            var saml2LogoutResponse = new Saml2LogoutResponse(samlConfig)
            {
                InResponseTo = new Saml2Id(inResponseTo),
                Status       = status,
                Destination  = new Uri(loggedOutUrl),
                SessionIndex = sessionIndex
            };

            binding.Bind(saml2LogoutResponse);
            logger.ScopeTrace($"SAML Logout response '{saml2LogoutResponse.XmlDocument.OuterXml}'.");
            logger.ScopeTrace($"Logged out url '{loggedOutUrl}'.");
            logger.ScopeTrace("Down, SAML Logout response.", triggerEvent: true);

            await sequenceLogic.RemoveSequenceDataAsync <SamlDownSequenceData>();

            await formActionLogic.RemoveFormActionSequenceDataAsync();

            if (binding is Saml2Binding <Saml2RedirectBinding> )
            {
                return(await Task.FromResult((binding as Saml2RedirectBinding).ToActionResult()));
            }
            if (binding is Saml2Binding <Saml2PostBinding> )
            {
                return(await Task.FromResult((binding as Saml2PostBinding).ToActionResult()));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
 public static string ToString(Saml2StatusCodes value)
 {
     return(toStrings[value]);
 }
示例#21
0
        private Task <IActionResult> AuthnResponseAsync(string partyId, Saml2Configuration samlConfig, string inResponseTo, string relayState, string acsUrl, SamlBindingType binding, Saml2StatusCodes status)
        {
            logger.ScopeTrace($"Authn response{(status != Saml2StatusCodes.Success ? " error" : string.Empty)}, Status code '{status}'.");
            logger.SetScopeProperty("downPartyId", partyId);

            logger.ScopeTrace($"Binding '{binding}'");
            switch (binding)
            {
            case SamlBindingType.Redirect:
                return(AuthnResponseAsync(samlConfig, inResponseTo, relayState, acsUrl, new Saml2RedirectBinding(), status));

            case SamlBindingType.Post:
                return(AuthnResponseAsync(samlConfig, inResponseTo, relayState, acsUrl, new Saml2PostBinding(), status));

            default:
                throw new NotSupportedException($"SAML binding '{binding}' not supported.");
            }
        }
示例#22
0
        private async Task <IActionResult> AuthnResponseAsync <T>(Saml2Configuration samlConfig, string inResponseTo, string relayState, string acsUrl, Saml2Binding <T> binding, Saml2StatusCodes status, SamlDownParty party = null, IEnumerable <Claim> claims = null)
        {
            binding.RelayState = relayState;

            var saml2AuthnResponse = new FoxIdsSaml2AuthnResponse(settings, samlConfig)
            {
                InResponseTo = new Saml2Id(inResponseTo),
                Status       = status,
                Destination  = new Uri(acsUrl),
            };

            if (status == Saml2StatusCodes.Success && party != null && claims != null)
            {
                claims = await claimTransformationsLogic.Transform(party.ClaimTransformations?.ConvertAll(t => (ClaimTransformation)t), claims);

                saml2AuthnResponse.SessionIndex = claims.FindFirstValue(c => c.Type == Saml2ClaimTypes.SessionIndex);

                saml2AuthnResponse.NameId = GetNameId(claims);

                var tokenIssueTime  = DateTimeOffset.UtcNow;
                var tokenDescriptor = saml2AuthnResponse.CreateTokenDescriptor(GetSubjectClaims(party, claims), party.Issuer, tokenIssueTime, party.IssuedTokenLifetime);

                var authnContext            = claims.FindFirstValue(c => c.Type == ClaimTypes.AuthenticationMethod);
                var authenticationInstant   = claims.FindFirstValue(c => c.Type == ClaimTypes.AuthenticationInstant);
                var authenticationStatement = saml2AuthnResponse.CreateAuthenticationStatement(authnContext, DateTime.Parse(authenticationInstant));

                var subjectConfirmation = saml2AuthnResponse.CreateSubjectConfirmation(tokenIssueTime, party.SubjectConfirmationLifetime);

                await saml2AuthnResponse.CreateSecurityTokenAsync(tokenDescriptor, authenticationStatement, subjectConfirmation);
            }

            binding.Bind(saml2AuthnResponse);
            logger.ScopeTrace($"SAML Authn response '{saml2AuthnResponse.XmlDocument.OuterXml}'.");
            logger.ScopeTrace($"Acs url '{acsUrl}'.");
            logger.ScopeTrace("Down, SAML Authn response.", triggerEvent: true);

            await sequenceLogic.RemoveSequenceDataAsync <SamlDownSequenceData>();

            await formActionLogic.RemoveFormActionSequenceDataAsync();

            if (binding is Saml2Binding <Saml2RedirectBinding> )
            {
                return(await Task.FromResult((binding as Saml2RedirectBinding).ToActionResult()));
            }
            else if (binding is Saml2Binding <Saml2PostBinding> )
            {
                return(await Task.FromResult((binding as Saml2PostBinding).ToActionResult()));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
示例#23
0
        private async Task <IActionResult> LogoutResponseDownAsync(SamlUpSequenceData sequenceData, Saml2StatusCodes status, string sessionIndex = null)
        {
            logger.ScopeTrace($"Response, Down type {sequenceData.DownPartyType}.");
            switch (sequenceData.DownPartyType)
            {
            case PartyTypes.OAuth2:
                throw new NotImplementedException();

            case PartyTypes.Oidc:
                if (status == Saml2StatusCodes.Success)
                {
                    return(await serviceProvider.GetService <OidcEndSessionDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().EndSessionResponseAsync(sequenceData.DownPartyId));
                }
                else
                {
                    throw new EndpointException($"SAML up Logout failed, Status '{status}', Name '{RouteBinding.UpParty.Name}'.")
                          {
                              RouteBinding = RouteBinding
                          };
                }

            case PartyTypes.Saml2:
                return(await serviceProvider.GetService <SamlLogoutDownLogic>().LogoutResponseAsync(sequenceData.DownPartyId, status, sessionIndex));

            default:
                throw new NotSupportedException();
            }
        }
 public static string ToString(Saml2StatusCodes value)
 {
     return toStrings[value];
 }