/// <summary>
        /// Logs the current configuration for troubleshooting purposes.
        /// </summary>
        private void LogCurrentConfiguration()
        {
            var sb = new StringBuilder();

            sb.AppendLine("Current plugin configuration");
            foreach (SettingsProperty settingsProperty in Settings.Default.Properties)
            {
                sb.AppendLine($"{settingsProperty.Name} : '{Settings.Default[settingsProperty.Name]}'");
            }

            sb.AppendLine("Plugin Metadata:");
            foreach (var am in this.Metadata.AuthenticationMethods)
            {
                sb.AppendLine($"AuthenticationMethod: '{am}'");
            }
            foreach (var ic in this.Metadata.IdentityClaims)
            {
                sb.AppendLine($"IdentityClaim: '{ic}'");
            }
            try
            {
                var options = Kentor.AuthServices.Configuration.Options.FromConfiguration;
                sb.AppendLine($"AssertionConsumerService: '{options.SPOptions.ReturnUrl.OriginalString}'");
                sb.AppendLine($"ServiceProvider.EntityId: '{Kentor.AuthServices.Configuration.Options.FromConfiguration.SPOptions.EntityId.Id}'");
                sb.AppendLine($"IdentityProvider.EntityId: '{SamlService.GetIdentityProvider(Kentor.AuthServices.Configuration.Options.FromConfiguration).EntityId.Id}'");
            }
            catch (Exception ex)
            {
                sb.AppendLine($"Error while reading configuration file. Please enter Serviceprovider en IdentityProvider settings. Details: {ex.Message}");
            }

            this.log.Info(sb);
        }
        /// <summary>
        /// Origina la petición de autenticacion a cl@ve
        /// </summary>
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                // Only react to 401 if there is an authentication challenge for the authentication
                // type of this handler.
                var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge != null)
                {
                    var state = challenge.Properties;

                    if (string.IsNullOrEmpty(state.RedirectUri))
                    {
                        state.RedirectUri = Request.Uri.ToString();
                    }

                    var stateString = Options.StateDataFormat.Protect(state);

                    SamlService claveSrv      = new SamlService();
                    var         commandResult = claveSrv.GetSamlCommandResult(stateString);
                    commandResult.Apply(Context);
                }
            }
            return(Task.FromResult <object>(null));
        }
        /// <summary>
        /// Validates the SAML response and set the necessary claims.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="proofData">The post back data.</param>
        /// <param name="request">The request.</param>
        /// <param name="claims">The claims.</param>
        /// <returns>A form if the the validation fails or claims if the validation succeeds.</returns>
        public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, HttpListenerRequest request, out Claim[] claims)
        {
            this.log.Debug("Enter TryEndAuthentication");
            this.log.DebugFormat("context.ActivityId='{0}'; context.ContextId='{1}'; conext.Lcid={2}", context.ActivityId, context.ContextId, context.Lcid);
            foreach (var d in context.Data)
            {
                this.log.DebugFormat("conext.Data: '{0}'='{1}'", d.Key, d.Value);
            }

            foreach (var p in proofData.Properties)
            {
                this.log.DebugFormat("proofData.Properties: '{0}'='{1}'", p.Key, p.Value);
            }

            claims = null;
            try
            {
                var response       = SecondFactorAuthResponse.Deserialize(proofData, context);
                var authnRequestId = $"_{ context.ContextId}";
                this.log.InfoFormat("Received response for request with id '{0}'", authnRequestId);
                var samlResponse = new Saml2Response(response.SamlResponse, new Saml2Id(authnRequestId));
                if (samlResponse.Status != Saml2StatusCode.Success)
                {
                    return(new AuthFailedForm(samlResponse.StatusMessage));
                }

                claims = SamlService.VerifyResponseAndGetAuthenticationClaim(samlResponse);
                foreach (var claim in claims)
                {
                    this.log.DebugFormat(
                        "claim.Issuer='{0}'; claim.OriginalIssuer='{1}; claim.Type='{2}'; claim.Value='{3}'",
                        claim.Issuer,
                        claim.OriginalIssuer,
                        claim.Type,
                        claim.Value);
                    foreach (var p in claim.Properties)
                    {
                        this.log.DebugFormat("claim.Properties: '{0}'='{1}'", p.Key, p.Value);
                    }
                }

                this.log.InfoFormat("Successfully processed response for request with id '{0}'", authnRequestId);
                return(null);
            }
            catch (Exception ex)
            {
                this.log.ErrorFormat("Error while processing the saml response. Details: {0}", ex);
                return(new AuthFailedForm());
            }
        }
Beispiel #4
0
        public ActionResult LoginSSO(string issuer)
        {
            var identity = SamlIdentityService.Get(issuer);

            if (identity == null)
            {
                return new ContentResult {
                           Content = string.Concat(@"SSO failed. \n Issuer ", issuer, " is invalid.")
                }
            }
            ;

            return(Redirect(string.Concat(identity.IssuerURL, SamlParam(identity.IssuerURL),
                                          Url.Encode(SamlService.GenerateRequest(identity, SamlService.GenerateId(), SamlService.IssueInstant())))));
        }
Beispiel #5
0
        public void ValidateSubject()
        {
            var claim   = new Claim("nameid", "homeorganization.nl:useridentifier");
            var request = SamlService.CreateAuthnRequest(claim, Guid.NewGuid().ToString(), new Uri("https://mytest.nl"));

            using (var service = new CryptographicService())
            {
                service.SignSamlRequest(request);
            }

            var requestXml = request.ToXElement();
            var ns         = XNamespace.Get("urn:oasis:names:tc:SAML:2.0:assertion");

            var element = requestXml.Element(ns + "Subject");

            Assert.IsNotNull(element);
            Assert.AreEqual(claim.Value, ((XElement)element.FirstNode).Value);
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            string rp = Request.Query["reqPath"];
            AuthenticationProperties authProp = Options.StateDataFormat.Unprotect(rp);

            SamlService claveSvc      = new SamlService();
            var         commandResult = claveSvc.GetSamlResponseCommandResult(await Context.ToHttpRequestData());

            if (commandResult.Principal != null)
            {
                var identity = commandResult.Principal.Identities
                               .Select(i => new ClaimsIdentity(i, null, Options.SignInAsAuthenticationType, i.NameClaimType, i.RoleClaimType)).FirstOrDefault();
                return(new AuthenticationTicket(identity, authProp));
            }
            else
            {
                return(new AuthenticationTicket(null, authProp));
            }
        }
Beispiel #7
0
        public ActionResult Consume(string issuer)
        {
            var response = new XmlResponse(Request.Form[SamlResponse]);
            var identity = SamlIdentityService.Get(issuer);

            if (identity == null)
            {
                return new ContentResult {
                           Content = string.Concat(@"SSO failed. \n Issuer ", issuer, " is invalid.")
                }
            }
            ;

            if (SamlService.ResponseIsValid(response, identity))
            {
                var userId = response.GetSubject();

                if (userId == null)
                {
                    return(Redirect(identity.IssuerLogoutUrl));
                }

                var token = SamlService.SetSsoToken(userId);
                if (token == null)
                {
                    return new ContentResult {
                               Content = string.Concat(@"SSO failed. \n User ", userId, " is invalid.")
                    }
                }
                ;

                return(Redirect(string.Concat(identity.AuthenticatedRedirectUrl, "?SSOtoken=", token, "&SamlIssuer=", identity.Issuer)));
            }
            return(new ContentResult {
                Content = @"SSO failed. \n Certificate is invalid."
            });
        }
        /// <summary>
        /// Begins the authentication.
        /// </summary>
        /// <param name="identityClaim">The identity claim.</param>
        /// <param name="httpListenerRequest">The HTTP listener request.</param>
        /// <param name="context">The context.</param>
        /// <returns>A presentation form.</returns>
        public IAdapterPresentation BeginAuthentication(Claim identityClaim, HttpListenerRequest httpListenerRequest, IAuthenticationContext context)
        {
            try
            {
                this.InitializeLogger();
                this.log.Debug("Enter BeginAuthentication");
                this.log.DebugFormat("context.ActivityId='{0}'; context.ContextId='{1}'; conext.Lcid={2}", context.ActivityId, context.ContextId, context.Lcid);

                string authnRequestId = $"_{context.ContextId}";
                var    authRequest    = SamlService.CreateAuthnRequest(identityClaim, authnRequestId, httpListenerRequest.Url);

                using (var cryptographicService = new CryptographicService())
                {
                    this.log.DebugFormat("Signing AuthnRequest with id {0}", authnRequestId);
                    var signedXml = cryptographicService.SignSamlRequest(authRequest);
                    return(new AuthForm(Settings.Default.SecondFactorEndpoint, signedXml));
                }
            }
            catch (Exception ex)
            {
                this.log.ErrorFormat("Error while initiating authentication:{0}", ex);
                return(new AuthFailedForm());
            }
        }