//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"));
        }
        /// <summary>
        /// Create a Claims Principal and a Federated Authentication Session for the authenticated user.
        /// </summary>
        /// <param name="lifetime">The period from the current time during which the token is valid. Default use the security token valid to time.</param>
        /// <param name="isReferenceMode">In reference mode, a simple artifact is produced during serialization and the token material is stored in the token cache that is associated with the token handler. The token cache is an instance of a class that derives from SessionSecurityTokenCache. For Web Farm scenarios, the token cache must operate across all nodes in the farm.</param>
        /// <param name="isPersistent">If the IsPersistent property is true, the cookie is written as a persistent cookie. Persistent cookies remain valid after the browser is closed until they expire.</param>
        /// <param name="claimsAuthenticationManager">Possible to add a custom ClaimsAuthenticationManager for handling claims transformation.</param>
        public static ClaimsPrincipal CreateSession(this Saml2AuthnResponse saml2AuthnResponse, TimeSpan?lifetime = null, bool isReferenceMode = false, bool isPersistent = false, ClaimsAuthenticationManager claimsAuthenticationManager = null)
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                throw new InvalidOperationException("There already exist an Authenticated user.");
            }

            if (saml2AuthnResponse.Status != Saml2StatusCodes.Success)
            {
                throw new InvalidOperationException($"The SAML2 Response Status is not Success, the Response Status is: {saml2AuthnResponse.Status}.");
            }

            var principal = new ClaimsPrincipal(saml2AuthnResponse.ClaimsIdentity);

            if (principal.Identity == null || !principal.Identity.IsAuthenticated)
            {
                throw new InvalidOperationException("No Claims Identity created from SAML2 Response.");
            }

            var transformedPrincipal = claimsAuthenticationManager != null?claimsAuthenticationManager.Authenticate(null, principal) : principal;

            var sessionSecurityToken = lifetime.HasValue ?
                                       new SessionSecurityToken(transformedPrincipal, lifetime.Value) :
                                       new SessionSecurityToken(transformedPrincipal, null, saml2AuthnResponse.Saml2SecurityToken.ValidFrom, saml2AuthnResponse.Saml2SecurityToken.ValidTo);

            sessionSecurityToken.IsReferenceMode = isReferenceMode;
            sessionSecurityToken.IsPersistent    = isPersistent;
            FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(sessionSecurityToken, true);
            return(transformedPrincipal);
        }
Exemplo n.º 3
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);
        }
        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));
        }
Exemplo n.º 5
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));
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
0
        private SAAuthenticationResponse DecodeAuthnResponse(Saml2AuthnResponse saml2AuthnResponse)
        {
            if (saml2AuthnResponse.Status != Saml2StatusCodes.Success)
            {
                throw new InvalidOperationException(
                          string.Format("The SAML2 Response Status is not Success, the Response Status is: {0}.",
                                        saml2AuthnResponse.Status));
            }
            var incomingPrincipal = new ClaimsPrincipal(saml2AuthnResponse.ClaimsIdentity);

            if (incomingPrincipal.Identity == null || !incomingPrincipal.Identity.IsAuthenticated)
            {
                throw new InvalidOperationException("No Claims Identity created from SAML2 Response.");
            }
            ClaimsPrincipal claimsPrincipal =
                FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager
                .Authenticate(null, incomingPrincipal);

            return(new SAAuthenticationResponse(claimsPrincipal.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));
        }
Exemplo n.º 9
0
        public void Resolve(IdpSsoService artifactResolutionService, Saml2AuthnResponse authnResponse)
        {
            var xmlDoc = this.ToXml();

            var soapEnvelope = new SOAPEnvelope();
            soapEnvelope.Body = xmlDoc;

            xmlDoc = soapEnvelope.ToSoapXml();
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            client.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=\"utf-8\"");
            client.Headers.Add(HttpRequestHeader.Accept, "text/xml");
            var result = client.UploadString(artifactResolutionService.Location, xmlDoc.OuterXml);

            soapEnvelope.FromSoapXml(result);

            var ares = new SamlArtifactResponse(authnResponse)
            {
                SignatureValidationCertificate = SignatureValidationCertificate
            };
            ares.Read(soapEnvelope.Body.OuterXml, SignatureValidationCertificate != null);


        }
 public SamlArtifactResponse(Saml2AuthnResponse response)
 {
     AuthnResponse = response;
 }
Exemplo n.º 11
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 }));
        }