Esempio n. 1
0
        public ActionResult Initiate()
        {
            var serviceProviderRealm = "https://claimstest.mylogbuy.com";

            var binding = new Saml2PostBinding();

            binding.RelayState = $"RPID={Uri.EscapeDataString(serviceProviderRealm)}";

            var config = new Saml2Configuration
            {
                Issuer = "http://some-domain.com/this-application",
                SingleSignOnDestination = new Uri("https://adfs.mylogbuy.com/adfs/ls/"),
                SigningCertificate      =
                    CertificateUtil.Load(
                        HttpContext.Server.MapPath("~/App_Data/itfoxtec.identity.saml2.testwebapp_Certificate.pfx"),
                        "!QAZ2wsx"),
                SignatureAlgorithm = Saml2SecurityAlgorithms.RsaSha256Signature
            };


            var appliesToAddress = "http://adfs.mylogbuy.com/adfs/services/trust";

            var response = new Saml2AuthnResponse(config);

            response.Status = Saml2StatusCodes.Success;

            var claimsIdentity = new ClaimsIdentity(CreateClaims());

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

            return(binding.Bind(response).ToActionResult());
        }
Esempio n. 2
0
        public async Task <IActionResult> SingleLogout()
        {
            var loginType = await GetSelectedLoginType();

            Saml2StatusCodes status;
            var requestBinding = new Saml2PostBinding();
            var logoutRequest  = new Saml2LogoutRequest(saml2Config, User);

            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), logoutRequest);
                status = Saml2StatusCodes.Success;
                await idPSelectionCookieRepository.DeleteAsync();

                await logoutRequest.DeleteSession(HttpContext);
            }
            catch (Exception exc)
            {
                // log exception
                Debug.WriteLine("SingleLogout error: " + exc.ToString());
                status = Saml2StatusCodes.RequestDenied;
            }

            var responsebinding = new Saml2PostBinding();

            responsebinding.RelayState = requestBinding.RelayState;
            var saml2LogoutResponse = new Saml2LogoutResponse(saml2Config)
            {
                InResponseToAsString = logoutRequest.IdAsString,
                Status = status,
            };

            saml2LogoutResponse.Destination = AddUpParty(saml2LogoutResponse.Destination, loginType);
            return(responsebinding.Bind(saml2LogoutResponse).ToActionResult());
        }
        public IActionResult Initiate()
        {
            var serviceProviderRealm = "https://some-domain.com/some-service-provider";

            var binding = new Saml2PostBinding();

            binding.RelayState = $"RPID={Uri.EscapeDataString(serviceProviderRealm)}";

            var config = new Saml2Configuration();

            config.Issuer = new Uri("http://some-domain.com/this-application");
            config.SingleSignOnDestination = new Uri("https://test-adfs.itfoxtec.com/adfs/ls/");
            config.SigningCertificate      = CertificateUtil.Load(Startup.AppEnvironment.MapToPhysicalFilePath("itfoxtec.identity.saml2.testwebappcore_Certificate.pfx"));
            config.SignatureAlgorithm      = SecurityAlgorithms.RsaSha256Signature;

            var appliesToAddress = new Uri("https://test-adfs.itfoxtec.com/adfs/services/trust");

            var response = new Saml2AuthnResponse(config);

            response.Status = Saml2StatusCodes.Success;

            var claimsIdentity = new ClaimsIdentity(CreateClaims());

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

            return(binding.Bind(response).ToActionResult());
        }
Esempio n. 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());
        }
Esempio n. 5
0
        public async Task <IActionResult> AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse(saml2Config);

            binding.ReadSamlResponse(Request.ToGenericHttpRequest(), saml2AuthnResponse);
            if (saml2AuthnResponse.Status != Saml2StatusCodes.Success)
            {
                throw new AuthenticationException($"SAML Response status: {saml2AuthnResponse.Status}");
            }
            binding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnResponse);

            await saml2AuthnResponse.CreateSession(HttpContext, claimsTransform : (claimsPrincipal) => ClaimsTransform.Transform(claimsPrincipal));

            var relayStateQuery = binding.GetRelayStateQuery();

            if (relayStateQuery.ContainsKey(relayStateLoginType))
            {
                var loginType = relayStateQuery[relayStateLoginType];
                await idPSelectionCookieRepository.SaveAsync(loginType);
            }
            var returnUrl = relayStateQuery.ContainsKey(relayStateReturnUrl) ? relayStateQuery[relayStateReturnUrl] : Url.Content("~/");

            return(Redirect(returnUrl));
        }
Esempio n. 6
0
        public async Task <IActionResult> SingleLogout()
        {
            var requestBinding = new Saml2PostBinding();
            var request        = new Saml2LogoutRequest(_configuration);
            Saml2StatusCodes status;

            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), request);
                await request.DeleteSession(HttpContext);

                status = Saml2StatusCodes.Success;
            }
            catch (Exception)
            {
                status = Saml2StatusCodes.RequestDenied;
            }

            var responseBinding = new Saml2PostBinding();

            responseBinding.RelayState = requestBinding.RelayState;

            var response = new Saml2LogoutResponse(_configuration)
            {
                InResponseToAsString = request.IdAsString,
                Status = status
            };

            return(responseBinding.Bind(response)
                   .ToActionResult());
        }
Esempio n. 7
0
 /// <summary>
 /// To Post Action Result
 /// </summary>
 public static ActionResult ToActionResult(this Saml2PostBinding binding)
 {
     return(new ContentResult
     {
         Content = binding.PostContent
     });
 }
Esempio n. 8
0
        public ActionResult SingleLogout()
        {
            Saml2StatusCodes status;
            var requestBinding = new Saml2PostBinding();
            var logoutRequest  = new Saml2LogoutRequest(config, ClaimsPrincipal.Current);

            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), logoutRequest);
                status = Saml2StatusCodes.Success;
                logoutRequest.DeleteSession();
            }
            catch (Exception exc)
            {
                // log exception
                Debug.WriteLine("SingleLogout error: " + exc.ToString());
                status = Saml2StatusCodes.RequestDenied;
            }

            var responsebinding = new Saml2PostBinding();

            responsebinding.RelayState = requestBinding.RelayState;
            var saml2LogoutResponse = new Saml2LogoutResponse(config)
            {
                InResponseToAsString = logoutRequest.IdAsString,
                Status = status,
            };

            return(responsebinding.Bind(saml2LogoutResponse).ToActionResult());
        }
Esempio n. 9
0
        public ActionResult Login(string returnUrl)
        {
            var binding = new Saml2PostBinding();

            binding.SetRelayStateQuery(new Dictionary <string, string> {
                { RelayStateReturnUrl, returnUrl }
            });

            return(binding.Bind(new Saml2AuthnRequest
            {
                ForceAuthn = false,
                IsPassive = false,
                NameIdPolicy =
                    new NameIdPolicy
                {
                    AllowCreate = true,
                    Format = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"
                },
                RequestedAuthnContext = new RequestedAuthnContext
                {
                    Comparison = AuthnContextComparisonTypes.Exact,
                    AuthnContextClassRef =
                        new[] { AuthnContextClassTypes.PasswordProtectedTransport.OriginalString }
                },
                Issuer = new EndpointReference(Constants.ConfigSettings.SAServiceProviderEntityId),
                Destination = new EndpointAddress(Constants.ConfigSettings.SADestination),
                AssertionConsumerServiceUrl =
                    new EndpointAddress(Constants.ConfigSettings.SAAssertionConsumerServiceUrl),
            }).ToActionResult());
        }
Esempio n. 10
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());
        }
Esempio n. 11
0
 public static Task <ContentResult> ToActionFormResultAsync(this Saml2PostBinding binding)
 {
     return(Task.FromResult(new ContentResult
     {
         ContentType = "text/html",
         Content = binding.PostContent,
     }));
 }
Esempio n. 12
0
        public void Saml2Binding_Get_NullOnPlainGet()
        {
            var r = Substitute.For <HttpRequestBase>();

            r.HttpMethod.Returns("GET");

            Saml2PostBinding.Get(r).Should().BeNull();
        }
 /// <summary>
 /// To Post Action Result
 /// </summary>
 public static IActionResult ToActionResult(this Saml2PostBinding binding)
 {
     return(new ContentResult
     {
         ContentType = "text/html",
         Content = binding.PostContent
     });
 }
        public IActionResult LoggedOut()
        {
            var binding = new Saml2PostBinding();

            binding.Unbind(Request.ToGenericHttpRequest(), new Saml2LogoutResponse(config));

            return(Redirect(Url.Content("~/")));
        }
Esempio n. 15
0
        public IActionResult LoggedOut()
        {
            var binding  = new Saml2PostBinding();
            var response = new Saml2LogoutResponse(_configuration);

            binding.Unbind(Request.ToGenericHttpRequest(), response);
            return(Redirect(Url.Action("Index", "Home")));
        }
Esempio n. 16
0
        public void Saml2Binding_Get_NullOnPlainPost()
        {
            var r = Substitute.For <HttpRequestBase>();

            r.HttpMethod.Returns("POST");
            r.Form.Returns(new NameValueCollection());

            Saml2PostBinding.Get(r).Should().BeNull();
        }
Esempio n. 17
0
        public ActionResult LoggedOut()
        {
            var binding = new Saml2PostBinding();

            binding.Unbind(Request.ToGenericHttpRequest(), new Saml2LogoutResponse(config));

            FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie();
            FederatedAuthentication.SessionAuthenticationModule.SignOut();

            return(Redirect(Url.Content("~/")));
        }
Esempio n. 18
0
        public void Saml2Binding_Get_Saml2Binding()
        {
            var r = Substitute.For <HttpRequestBase>();

            r.HttpMethod.Returns("POST");
            r.Form.Returns(new NameValueCollection()
            {
                { "SAMLResponse", "someData" }
            });

            Saml2PostBinding.Get(r).Should().BeOfType <Saml2PostBinding>();
        }
        public async Task <IActionResult> AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse(config);

            binding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnResponse);
            await saml2AuthnResponse.CreateSession(HttpContext, claimsTransform : (claimsPrincipal) => ClaimsTransform.Transform(claimsPrincipal));

            var returnUrl = binding.GetRelayStateQuery()[relayStateReturnUrl];

            return(Redirect(string.IsNullOrWhiteSpace(returnUrl) ? Url.Content("~/") : returnUrl));
        }
Esempio n. 20
0
        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));
        }
Esempio n. 21
0
        public async Task <IActionResult> AssertionConsumer()
        {
            var binding  = new Saml2PostBinding();
            var response = new FixedSaml2AuthnResponse(_configuration);

            binding.Unbind(Request.ToGenericHttpRequest(), response);
            await response.CreateSession(HttpContext, ClaimsTransform : principal => ClaimsPrincipalHelper.Transform(principal));

            var returnUrl = binding.GetRelayStateQuery()[ReturnUrlRelayStateKey];

            return(Redirect(returnUrl));
        }
Esempio n. 22
0
        private IActionResult SingleLogoutResponseInternal()
        {
            var responseBinding = new Saml2PostBinding();
            var relyingParty    = ValidateRelyingParty(ReadRelyingPartyFromLogoutResponse(responseBinding));

            var saml2LogoutResponse = new Saml2LogoutResponse(saml2Config);

            saml2LogoutResponse.SignatureValidationCertificates = new X509Certificate2[] { relyingParty.SignatureValidationCertificate };
            responseBinding.Unbind(Request.ToGenericHttpRequest(), saml2LogoutResponse);

            return(Redirect(Url.Content("~/")));
        }
        public ActionResult Logout()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect(Url.Content("~/")));
            }

            var binding       = new Saml2PostBinding();
            var logoutRequest = new Saml2LogoutRequest(config, ClaimsPrincipal.Current).DeleteSession();

            return(binding.Bind(logoutRequest).ToActionResult());
        }
Esempio n. 24
0
        public async Task <IActionResult> Logout()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect(Url.Content("~/")));
            }

            var binding            = new Saml2PostBinding();
            var saml2LogoutRequest = await new Saml2LogoutRequest(_samlConfig, User).DeleteSession(HttpContext);

            return(Redirect("~/"));
        }
Esempio n. 25
0
        public ActionResult AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse(config);

            binding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnResponse);

            saml2AuthnResponse.CreateSession(claimsAuthenticationManager: new DefaultClaimsAuthenticationManager());

            var returnUrl = binding.GetRelayStateQuery()[relayStateReturnUrl];

            return(Redirect(string.IsNullOrWhiteSpace(returnUrl) ? Url.Content("~/") : returnUrl));
        }
        protected virtual async Task ApplyResponseLogoutAsync()
        {
            var options = Options as Saml2AuthenticationOptions;

            if (options == null)
            {
                return;
            }

            if (_configuration == null)
            {
                _configuration = await options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
            }

            var request = Context.Get <HttpContextBase>(typeof(HttpContextBase).FullName).Request;

            foreach (var signingKey in _configuration.SigningKeys.OfType <X509SecurityKey>())
            {
                var binding = new Saml2PostBinding();
                Saml2LogoutResponse response = null;

                try
                {
                    response = binding.Unbind(request, new Saml2LogoutResponse(), signingKey.Certificate) as Saml2LogoutResponse;
                }
                catch (Saml2ResponseException)
                {
                }

                if (response == null || response.Status != Saml2StatusCodes.Success)
                {
                    continue;
                }

                var relayState = binding.GetRelayStateQuery();
                var properties = relayState.ContainsKey(_relayStateWctx)
                                        ? Options.StateDataFormat.Unprotect(relayState[_relayStateWctx])
                                        : new AuthenticationProperties();

                if (string.IsNullOrWhiteSpace(properties.RedirectUri))
                {
                    properties.RedirectUri = GetRedirectUri(binding, options);
                }

                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RedirectUri={0}", properties.RedirectUri));

                Response.Redirect(properties.RedirectUri);

                return;
            }
        }
Esempio n. 27
0
        public async Task <IActionResult> LogOut()
        {
            if (User.Identity.IsAuthenticated)
            {
                var binding = new Saml2PostBinding();
                var request = new Saml2LogoutRequest(_configuration);
                await request.DeleteSession(HttpContext);

                return(binding.Bind(request)
                       .ToActionResult());
            }

            return(Redirect(Url.Action("Index", "Home")));
        }
        public ActionResult Logout()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect(Url.Content("~/")));
            }

            var binding = new Saml2PostBinding();

            return(binding.Bind(new Saml2LogoutRequest
            {
                Issuer = new EndpointReference("http://udv.itfoxtec.com/webapptest"),
                Destination = new EndpointAddress("https://udv.itfoxtec.com/adfs/ls/")
            }, CertificateUtil.Load("~/App_Data/webapptest_certificate.pfx")).ToActionResult());
        }
Esempio n. 29
0
        public async Task <IActionResult> SingleLogout()
        {
            var session = await idPSessionCookieRepository.GetAsync();

            var relyingParty = ValidateRelyingParty(session.RelyingPartyIssuer);

            var binding            = new Saml2PostBinding();
            var saml2LogoutRequest = new Saml2LogoutRequest(saml2Config, User)
            {
                Destination = relyingParty.SingleLogoutDestination
            };

            await idPSessionCookieRepository.DeleteAsync();

            return(binding.Bind(saml2LogoutRequest).ToActionResult());
        }
Esempio n. 30
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());
        }