Exemplo n.º 1
0
        public async Task Execute(IEnumerable <CommitContext> context, Next <IEnumerable <CommitContext> > next)
        {
            var items = context.ToList();

            await next(items);

            foreach (var item in items)
            {
                switch (item.ActionType)
                {
                case ActionType.Update:
                    continue;

                case ActionType.Add:
                    var entry = _sessionCache[item.Key];
                    entry.Action = ActionType.Update;
                    break;

                default:
                    _sessionCache.Remove(item.Key);
                    break;
                }
            }
        }
Exemplo n.º 2
0
        public virtual void CreateUninitializedItem(IAspEnvironmentContext context, string id, int timeOut)
        {
            try
            {
                _cache.IsSessionCookieless = IsSessionCookieless(context);
                PutInNCache(context, id, InsertContents(context, null, SessionInitializationActions.InitializeItem, timeOut), null, true);
                if (_detailedLogs)
                {
                    LogDebug("New session added to cache.", id);
                }
            }
            catch (Exception)
            {
                try
                {
                    if (_cache != null)
                    {
                        string locationID = GetLocationID(context, id);
                        _cache.Remove(locationID, GetUniqueSessionId(id), false);
                    }
                }
                catch (Exception)
                {
                }

                try
                {
                    PutInNCache(context, id, InsertContents(context, null, SessionInitializationActions.InitializeItem, timeOut), null, false);
                    if (_detailedLogs)
                    {
                        LogDebug("New session added to cache.", id);
                    }
                }
                catch (Exception exc)
                {
                    LogError(exc, id);
                }
            }
        }
Exemplo n.º 3
0
        public override void CreateUninitializedItem(HttpContext context, string id, int timeOut)
        {
            try
            {
                PutInNCache(id, InsertContents(context, null, SessionStateActions.InitializeItem, timeOut), null, true);
                if (_detailedLogs)
                {
                    NCacheLog.Debug(id + " :new session added to cache.");
                }
            }
            catch (Exception)
            {
                try
                {
                    if (_cache != null)
                    {
                        _cache.Remove(GetUniqueSessionId(id), false);
                    }
                }
                catch (Exception)
                {
                }

                try
                {
                    PutInNCache(id, InsertContents(context, null, SessionStateActions.InitializeItem, timeOut), null, false);
                    if (_detailedLogs)
                    {
                        NCacheLog.Debug(id + " :new session added to cache.");
                    }
                }
                catch (Exception exc)
                {
                    RaiseException(exc, id);
                }
            }
        }
Exemplo n.º 4
0
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            Collection <XmlElement> reqParams = new Collection <XmlElement>();

            foreach (XmlElement param in tokenRequirement.AdditionalRequestParameters)
            {
                if (param.NamespaceURI == "urn:oasis:names:tc:SAML:1.0:assertion")
                {
                    reqParams.Add(param);
                }
            }

            ISessionCache cache = (ISessionCache)Activator.CreateInstance(clientCredentials.Cache, clientCredentials.Config);

            //Check the cache for existing session.
            String        id;
            List <String> idSort;

            id     = clientCredentials.ClientCertificate.Certificate.Thumbprint + ";";
            id    += clientCredentials.Session.Thumbprint + ";";
            idSort = new List <string>();
            foreach (XmlElement reqParam in reqParams)
            {
                String val;
                val  = "{" + reqParam.GetAttribute("AttributeNamespace") + "}";
                val += reqParam.GetAttribute("AttributeName");
                val += "=";
                val += reqParam.GetElementsByTagName("AttributeValue", "urn:oasis:names:tc:SAML:1.0:assertion")[0].InnerText;
                val += ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }
            idSort = new List <string>();
            foreach (ClaimTypeRequirement req in tokenRequirement.ClaimTypeRequirements)
            {
                String val = req.ClaimType + ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }

            XmlNamespaceManager nsmngr       = null;
            DateTime            notOnOrAfter = DateTime.MinValue;

            //Get the value from the cache
            XmlElement assertion = cache.Get(id);

            //If cache had a result, check if it is still valid
            if (assertion != null)
            {
                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                if (notOnOrAfter < DateTime.UtcNow)
                {
                    assertion = null;
                    cache.Remove(id);
                }
            }

            //If the cache wasn't successful, create new.
            if (assertion == null)
            {
                //Get a new assertion token for the session
                StsClient target = new StsClient(tokenRequirement.IssuerBinding, tokenRequirement.IssuerAddress);
                target.Endpoint.Behaviors.Remove <ClientCredentials>();
                target.Endpoint.Behaviors.Add(new OptClientCredentials());
                target.ClientCredentials.ClientCertificate.Certificate = clientCredentials.ClientCertificate.Certificate;
                target.InnerChannel.OperationTimeout = timeout;

                assertion = target.RequestTicket("Anonymous", clientCredentials.Session, clientCredentials.Duration, reqParams, tokenRequirement.ClaimTypeRequirements);

                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                cache.Add(id, assertion, notOnOrAfter);
            }

            //Get some date from the assertion token
            DateTime notBefore   = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotBefore", nsmngr).Value, null, DateTimeStyles.RoundtripKind);
            String   assertionId = assertion.SelectSingleNode("@AssertionID", nsmngr).Value;

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = new SamlAssertionKeyIdentifierClause(assertionId);

            return(new GenericXmlSecurityToken(assertion, new X509SecurityToken(clientCredentials.Session), notBefore, notOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null));
        }
Exemplo n.º 5
0
        public SessionModule(IUserRepository userRepository, ISessionCache sessionCache)
        {
            Get["/api/sessions/{value}"] = x =>
            {
                var guid    = (Guid)x.value;
                var session = sessionCache.Get(guid);
                if (session == null)
                {
                    return(new
                    {
                        isAuthenticated = false,
                    });
                }

                return(new
                {
                    userId = session.User.Id,
                    firstName = session.User.FirstName,
                    lastName = session.User.LastName,
                    isAuthenticated = true
                });
            };

            Post["/api/sessions"] = x =>
            {
                var guid     = (Guid)Request.Form.Id;
                var username = (string)Request.Form.Username;
                var password = (string)Request.Form.Password;

                if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password))
                {
                    return(HttpStatusCode.Unauthorized);
                }

                var user = userRepository.FindByUsernameAndPassword(username, password);
                if (user == null)
                {
                    return(HttpStatusCode.Unauthorized);
                }

                var session = new Session {
                    Id = guid, User = user
                };
                sessionCache.Set(guid, session);

                return(new
                {
                    id = guid,
                    isAuthenticated = true,
                    userID = user.Id,
                    firstName = user.FirstName,
                    lastName = user.LastName
                });
            };

            Delete["/api/sessions/{value:guid}"] = x =>
            {
                sessionCache.Remove(x.value);
                return(HttpStatusCode.NoContent);
            };
        }