Esempio n. 1
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. 2
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. 4
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. 5
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. 7
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"));
        }
        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);
        }
Esempio n. 10
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 }));
        }