//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"));
        }
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());
        }
Esempio n. 3
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. 4
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. 5
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());
        }
        public IActionResult LoggedOut()
        {
            var binding = new Saml2PostBinding();

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

            return(Redirect(Url.Content("~/")));
        }
Esempio n. 7
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. 8
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. 9
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));
        }
        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. 11
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. 12
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("~/")));
        }
Esempio n. 13
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. 15
0
        public ActionResult AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse(config);

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

            var relayStateQuery = binding.GetRelayStateQuery();
            var returnUrl       = relayStateQuery.ContainsKey(relayStateReturnUrl) ? relayStateQuery[relayStateReturnUrl] : Url.Content("~/");

            return(Redirect(returnUrl));
        }
        public ActionResult AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse();

            X509Certificate2 certificate = CertificateUtil.Load(Configuration.PATH_TO_CERTIFICATE);

            binding.Unbind(Request, saml2AuthnResponse, certificate);
            saml2AuthnResponse.CreateSession();

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

            if (!string.IsNullOrWhiteSpace(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToAction("Claims"));
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            //AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            //if (!result.IsSuccessful)
            //{
            //    return RedirectToAction("ExternalLoginFailure");
            //}

            //if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            //{
            //    return RedirectToLocal(returnUrl);
            //}

            //if (User.Identity.IsAuthenticated)
            //{
            //    // If the current user is logged in add the new account
            //    OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
            //    return RedirectToLocal(returnUrl);
            //}
            //else
            //{
            //    // User is new, ask for their desired membership name
            //    string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
            //    ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
            //    ViewBag.ReturnUrl = returnUrl;
            //    return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            //}

            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse();


            var saml2Response = binding.Unbind(Request, saml2AuthnResponse, CertificateUtil.Load("~/App_Data/idp-signing.crt"));

            saml2AuthnResponse.CreateSession();

            bool testAuth = User.Identity.IsAuthenticated;

            return(RedirectToLocal(returnUrl));
        }
Esempio n. 18
0
        private async Task <IActionResult> LogoutInternal()
        {
            var requestBinding = new Saml2PostBinding();
            var relyingParty   = ValidateRelyingParty(ReadRelyingPartyFromLogoutRequest(requestBinding));

            var saml2LogoutRequest = new Saml2LogoutRequest(saml2Config);

            saml2LogoutRequest.SignatureValidationCertificates = new X509Certificate2[] { relyingParty.SignatureValidationCertificate };
            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2LogoutRequest);

                await idPSessionCookieRepository.DeleteAsync();

                return(LogoutResponse(saml2LogoutRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, saml2LogoutRequest.SessionIndex, relyingParty));
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex, $"SAML 2.0 Logout Request error. Logout Request '{saml2LogoutRequest.XmlDocument?.OuterXml}'.");
                return(LogoutResponse(saml2LogoutRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, saml2LogoutRequest.SessionIndex, relyingParty));
            }
        }
Esempio n. 19
0
        public IActionResult Logout()
        {
            var requestBinding = new Saml2PostBinding();
            var relyingParty   = ValidateRelyingParty(ReadRelyingPartyFromLogoutRequest(requestBinding));

            var saml2LogoutRequest = new Saml2LogoutRequest(config);

            saml2LogoutRequest.SignatureValidationCertificates = new X509Certificate2[] { relyingParty.SignatureValidationCertificate };
            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2LogoutRequest);

                // **** Delete user session ****

                return(LogoutResponse(saml2LogoutRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, saml2LogoutRequest.SessionIndex, relyingParty));
            }
            catch (Exception exc)
            {
#if DEBUG
                Debug.WriteLine($"Saml 2.0 Logout Request error: {exc.ToString()}\nSaml Logout Request: '{saml2LogoutRequest.XmlDocument?.OuterXml}'");
#endif
                return(LogoutResponse(saml2LogoutRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, saml2LogoutRequest.SessionIndex, relyingParty));
            }
        }
        public ActionResult Post()
        {
            var requestBinding = new Saml2PostBinding();
            var relyingParty   = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding));

            var saml2AuthnRequest = new Saml2AuthnRequest(config.IDP);

            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest);

                // ****  Handle user login e.g. in GUI ****
                // Test user with session index and claims
                var sessionIndex = Guid.NewGuid().ToString();

                var claims = GetClaimsFromCertificate(this.Request.ClientCertificate);

                return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, sessionIndex, claims));
            }
            catch (Exception exc)
            {
                return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty));
            }
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            var options = Options as Saml2AuthenticationOptions;

            if (options == null)
            {
                ADXTrace.Instance.TraceWarning(TraceCategory.Application, "AuthenticateCoreAsync:options == null");

                return(null);
            }

            if (options.CallbackPath.HasValue && options.CallbackPath != (Request.PathBase + Request.Path))
            {
                ADXTrace.Instance.TraceWarning(TraceCategory.Application,
                                               string.Format(
                                                   "AuthenticateCoreAsync:options.CallbackPath.HasValue && options.CallbackPath != (Request.PathBase: {0} + Request.Path: {1})",
                                                   Request.PathBase, Request.Path));
                return(null);
            }

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

            if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase) &&
                !string.IsNullOrWhiteSpace(Request.ContentType) &&
                Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) &&
                Request.Body.CanRead)
            {
                var request     = GetHttpRequestBase();
                var signingKeys = _configuration.SigningKeys.OfType <X509SecurityKey>().ToList();
                var totalKeys   = signingKeys.Count;
                var keyIndex    = 0;
                foreach (var signingKey in signingKeys)
                {
                    keyIndex++;
                    var binding = new Saml2PostBinding();
                    Saml2AuthnResponse response = null;

                    try
                    {
                        response = binding.Unbind(request, GetSaml2AuthnResponse(options), signingKey.Certificate) as Saml2AuthnResponse;
                    }
                    catch (Saml2ResponseException saml2ResponseException)
                    {
                        WebEventSource.Log.GenericWarningException(saml2ResponseException);
                    }

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

                    ADXTrace.Instance.TraceInfo(TraceCategory.Application,
                                                string.Format("Received the response for signing key with index:{0} out of:{1}", keyIndex, totalKeys));


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

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

                    var claimsIdentity = new ClaimsIdentity(response.ClaimsIdentity.Claims, options.TokenValidationParameters.AuthenticationType, response.ClaimsIdentity.NameClaimType, response.ClaimsIdentity.RoleClaimType);
                    var ticket         = new AuthenticationTicket(claimsIdentity, properties);

                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Identity={0}", ticket.Identity.Name));
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RedirectUri={0}", ticket.Properties.RedirectUri));

                    if (options.UseTokenLifetime)
                    {
                        var issued = response.Saml2SecurityToken.ValidFrom;

                        if (issued != DateTime.MinValue)
                        {
                            ticket.Properties.IssuedUtc = issued.ToUniversalTime();
                        }

                        var expires = response.Saml2SecurityToken.ValidTo;

                        if (expires != DateTime.MinValue)
                        {
                            ticket.Properties.ExpiresUtc = expires.ToUniversalTime();
                        }

                        ticket.Properties.AllowRefresh = false;
                    }

                    return(ticket);
                }
                ADXTrace.Instance.TraceWarning(TraceCategory.Application,
                                               string.Format("No response received for any signing keys. totalKeys found:{0}", totalKeys));
            }

            return(null);
        }
        protected virtual async Task ApplyRequestLogoutAsync()
        {
            var options = Options as Saml2AuthenticationOptions;

            if (options == null)
            {
                return;
            }

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

            var issuer      = options.Wtrealm;
            var destination = _configuration.TokenEndpoint ?? string.Empty;

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

            foreach (var signingKey in _configuration.SigningKeys.OfType <X509SecurityKey>())
            {
                Saml2StatusCodes status;

                var requestBinding = new Saml2PostBinding();
                var logoutRequest  = new Saml2LogoutRequest();

                try
                {
                    try
                    {
                        requestBinding.Unbind(request, logoutRequest, signingKey.Certificate);
                    }
                    catch (Saml2ResponseException)
                    {
                        continue;
                    }

                    status = Saml2StatusCodes.Success;
                }
                catch (Exception e)
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
                    status = Saml2StatusCodes.RequestDenied;
                }

                var responsebinding = new Saml2RedirectBinding {
                    RelayState = requestBinding.RelayState
                };

                var saml2LogoutResponse = new Saml2LogoutResponse
                {
                    InResponseTo = logoutRequest.Id,
                    Status       = status,
                    Issuer       = new EndpointReference(issuer),
                    Destination  = new EndpointAddress(destination)
                };

                Context.Authentication.SignOut();

                var redirectBinding  = responsebinding.Bind(saml2LogoutResponse, options.SigningCertificate);
                var redirectLocation = redirectBinding.RedirectLocation.AbsoluteUri;

                if (!Uri.IsWellFormedUriString(redirectLocation, UriKind.Absolute))
                {
                    ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("The sign-out redirect URI is malformed: {0}", redirectLocation));
                }

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

                Response.Redirect(redirectLocation);
            }
        }
Esempio n. 23
0
        public async Task <ActionResult> AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse();

            binding.Unbind(Request, saml2AuthnResponse, CertificateUtil.Load(Constants.ConfigSettings.SAX509Certificate));

            SAAuthenticationResponse claims;

            try
            {
                claims = DecodeAuthnResponse(saml2AuthnResponse);
            }
            catch (Exception e)
            {
                AppGlobal.Log.WriteLog(String.Format("Secure Access - Decoding AuthnResponse failed due to {0}.",
                                                     e.InnerException));
                ViewBag.MessageHtml = AppGlobal.Language.GetText(this, "SSOLogInFailed",
                                                                 "Log in failed for DfE Secure Access. If you believe you should have access to the Post 16 Provider Portal please contact the DfE Support Team on <a href='tel:08448115028'>0844 8115 028</a> or <a href='mailto:[email protected]'>[email protected]</a>.");
                ViewBag.ButtonText = AppGlobal.Language.GetText(this, "BackToSecureAccessButton",
                                                                "Back to Secure Access");
                ViewBag.ButtonUrl = Constants.ConfigSettings.SAHomePage;
                return(View("Info"));
            }

            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                AuthenticationManager.SignOut();
                SessionManager.End();
            }

            UserResponse userResult = await GetUserAsync(claims);

            if (!String.IsNullOrEmpty(userResult.Message))
            {
                ViewBag.MessageHtml = userResult.Message;
                ViewBag.MessageHtml = userResult.Message;
                ViewBag.ButtonText  = AppGlobal.Language.GetText(this, "BackToSecureAccessButton",
                                                                 "Back to Secure Access");
                ViewBag.ButtonUrl = Constants.ConfigSettings.SAHomePage;
                return(View("Info"));
            }

            ProviderResponse providerResult = await GetValidatedProviderAsync(claims, userResult.User.Id);

            if (!String.IsNullOrEmpty(providerResult.Message))
            {
                ViewBag.MessageHtml = providerResult.Message;
                ViewBag.ButtonText  = AppGlobal.Language.GetText(this, "BackToSecureAccessButton",
                                                                 "Back to Secure Access");
                ViewBag.ButtonUrl = Constants.ConfigSettings.SAHomePage;
                return(View("Info"));
            }

            // Associate user with the provider
            if (!userResult.User.Providers2.Any() ||
                userResult.User.Providers2.All(x => x.ProviderId != providerResult.Provider.ProviderId))
            {
                userResult.User.Providers2.Clear();
                userResult.User.Providers2.Add(providerResult.Provider);
            }
            userResult.User.LastLoginDateTimeUtc = DateTime.UtcNow;
            await db.SaveChangesAsync();

            // Actually log them in
            ApplicationUser user = await UserManager.FindByIdAsync(userResult.User.Id);

            await SignInManager.SignInAsync(user, true, false);

            // If we are doing a SAML2 log out we need to store this information for later use.
            // Set some extra properties so we can log out later
            //CacheManagement.CacheHandler.Add("SAML2Claims:" + aspNetUser.Id, new List<Claim>
            //{
            //    new Claim(Saml2ClaimTypes.NameId, claims.NameId),
            //    new Claim(Saml2ClaimTypes.NameIdFormat, claims.NameIdFormat),
            //    new Claim(Saml2ClaimTypes.SessionIndex, claims.SessionIndex),
            //});

            SessionManager.Start();

            // Bounce them via the following page so that their session is instantiated correctly
            string returnUrl = binding.GetRelayStateQuery()[RelayStateReturnUrl];

            return(RedirectToAction("LogInComplete", new { returnUrl }));
        }