Esempio n. 1
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            IAzManStorage storage = new SqlAzManStorage("data source=(local);Initial Catalog=NetSqlAzManStorage;user id=sa;password="******"Store Stress Test", "Application0", "Role0", this.Request.LogonUserIdentity, DateTime.Now, false).ToString();
                this.TextBox1.Text += storage.CheckAccess("Store Stress Test", "Application0", "Operation0", this.Request.LogonUserIdentity, DateTime.Now, false).ToString();
            }
            //Application0.Security.CheckAccessHelper chk = new Application0.Security.CheckAccessHelper("data source=.;Initial Catalog=NetSqlAzManStorage;Integrated Security=SSPI", this.Request.LogonUserIdentity);

//            this.TextBox1.Text = chk.CheckAccess(Application0.Security.CheckAccessHelper.Operation.Operation0).ToString();
        }
Esempio n. 2
0
        /// <summary>
        /// Check Access from your Application [FOR Windows Users ONLY].
        /// </summary>
        /// <param name="dbUserName">DB Username</param>
        private void CheckAccessPermissionsForDBUsers(string dbUserName)
        {
            // REMBER:
            // Modify dbo.GetDBUsers Table-Function to customize DB User list.
            // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Readers
            //Sql Storage connection string
            string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password";
            //Create an instance of SqlAzManStorage class
            IAzManStorage storage = new SqlAzManStorage(sqlConnectionString);
            //Retrieve DB User identity from dbo.GetDBUsers Table-Function
            IAzManDBUser      dbUser = storage.GetDBUser(dbUserName);
            AuthorizationType auth   = storage.CheckAccess("My Store", "My Application", "My Operation", dbUser, DateTime.Now, true);

            switch (auth)
            {
            case AuthorizationType.AllowWithDelegation:
                //Yes, I can ... and I can delegate
                break;

            case AuthorizationType.Allow:
                //Yes, I can
                break;

            case AuthorizationType.Neutral:
            case AuthorizationType.Deny:
                //No, I cannot
                break;
            }
        }
Esempio n. 3
0
    private AuthorizationType NetSqlAzManTestDirectCheckAccess()
    {
        WindowsIdentity userIdentity = this.Request.LogonUserIdentity;
        IAzManStorage   storage      = new SqlAzManStorage(NetSqlAzManStorePath);

        return(storage.CheckAccess("Store Test", "Application Test", this.txtDirectItem.Text, userIdentity, DateTime.Now, true));
    }
Esempio n. 4
0
 /// <summary>
 /// Determines whether the specified control name has access.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="controlName">Name of the control.</param>
 /// <param name="itemName">Name of the item.</param>
 /// <returns>
 ///     <c>true</c> if the specified control name has access; otherwise, <c>false</c>.
 /// </returns>
 protected internal bool HasAccess(NetSqlAzManAuthorizationContext context, string controlName, string itemName)
 {
     if (!String.IsNullOrEmpty(context._storageConnectionString))
     {
         if (context.StorageCache != null)
         {
             //Storage Cache
             AuthorizationType auth = AuthorizationType.Neutral;
             if (context._windowIdentity != null)
             {
                 auth = context.StorageCache.CheckAccess(context.StoreName, context.ApplicationName, itemName, context._windowIdentity.GetUserBinarySSid(), context._windowIdentity.GetGroupsBinarySSid(), ValidFor.HasValue ? ValidFor.Value : DateTime.Now, OperationsOnly, ContextParameters);
             }
             else if (context._dbuserIdentity != null)
             {
                 auth = context.StorageCache.CheckAccess(context.StoreName, context.ApplicationName, itemName, context._dbuserIdentity.CustomSid.StringValue, ValidFor.HasValue ? ValidFor.Value : DateTime.Now, OperationsOnly, ContextParameters);
             }
             return((auth == AuthorizationType.AllowWithDelegation) || (auth == AuthorizationType.Allow));
         }
         else
         {
             //Direct Access
             using (SqlAzManStorage storage = new SqlAzManStorage(context._storageConnectionString))
             {
                 AuthorizationType auth = AuthorizationType.Neutral;
                 if (context._windowIdentity != null)
                 {
                     auth = storage.CheckAccess(context.StoreName, context.ApplicationName, itemName, context._windowIdentity, ValidFor.HasValue ? ValidFor.Value : DateTime.Now, OperationsOnly, ContextParameters);
                 }
                 else if (context._dbuserIdentity != null)
                 {
                     auth = storage.CheckAccess(context.StoreName, context.ApplicationName, itemName, context._dbuserIdentity, ValidFor.HasValue ? ValidFor.Value : DateTime.Now, OperationsOnly, ContextParameters);
                 }
                 return((auth == AuthorizationType.AllowWithDelegation) || (auth == AuthorizationType.Allow));
             }
         }
     }
     else
     {
         throw new InvalidOperationException("NetSqlAzMan Storage connection string and NetSqlAzMan WCF Cache Service url cannot be both null");
     }
 }
Esempio n. 5
0
        private void TestSuNetSqlAzMan(string connectionString, int max)
        {
            WindowsIdentity id      = WindowsIdentity.GetCurrent();
            int             rnd     = new Random().Next(max);
            IAzManStorage   storage = new SqlAzManStorage(connectionString);

            storage.OpenConnection();
            AuthorizationType res = storage.CheckAccess("Store Stress Test", "Application" + rnd.ToString(), "Operation" + rnd.ToString(), id, DateTime.Now, true, new KeyValuePair <string, object>("chiave", "valore"));

            //AuthorizationType res = storage.CheckAccess("Store Stress Test", "Application" + rnd.ToString(), "Operation" + rnd.ToString(), storage.GetDBUser("Andrea"), DateTime.Now, true, new KeyValuePair<string, object>("chiave", "valore"));
            storage.CloseConnection();
            storage.Dispose();
        }
Esempio n. 6
0
        /// <summary>
        /// Check Access from your Application [FOR Windows Users ONLY].
        /// </summary>
        /// <param name="userIdentity">Windows User Identity.</param>
        private void CheckAccessPermissionsForWindowsUsers(WindowsIdentity userIdentity, bool useCache)
        {
            // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Readers

            //Sql Storage connection string
            string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password";
            //Create an instance of SqlAzManStorage class
            IAzManStorage storage = new SqlAzManStorage(sqlConnectionString);
            //To Pass current user identity:
            //WindowsIdentity.GetCurrent() -> for Windows Applications
            //this.Request.LogonUserIdentity -> for ASP.NET Applications
            List <KeyValuePair <string, string> > attributes;
            AuthorizationType auth;

            if (useCache)
            {
                //Build the cache Only one time per session/application/user
                NetSqlAzMan.Cache.UserPermissionCache cache = new NetSqlAzMan.Cache.UserPermissionCache(storage, "My Store", "My Application", userIdentity, true, true);
                //Then Check Access
                auth = cache.CheckAccess("My Operation", DateTime.Now, out attributes);
            }
            else
            {
                auth = storage.CheckAccess("My Store", "My Application", "My Operation", userIdentity, DateTime.Now, true, out attributes);
            }
            switch (auth)
            {
            case AuthorizationType.AllowWithDelegation:
                //Yes, I can ... and I can delegate
                break;

            case AuthorizationType.Allow:
                //Yes, I can
                break;

            case AuthorizationType.Neutral:
            case AuthorizationType.Deny:
                //No, I cannot
                break;
            }
            //Do something with attributes found
        }
Esempio n. 7
0
        private void buildApplicationCacheMultiThread()
        {
            try
            {
                DateTime globalNow = DateTime.Now;
                this.storage.OpenConnection();
                this.collectPermissionData();
                List <ItemCheckAccessResult> results = new List <ItemCheckAccessResult>();
                IAzManSid sid = this.windowsIdentity != null ? new SqlAzManSID(this.windowsIdentity.User) : this.dbUser.CustomSid;
                List <ManualResetEvent> waitHandles = new List <ManualResetEvent>();
                Hashtable allResult     = new Hashtable();
                int       index         = 0;
                Exception lastException = null;

                foreach (String itemname in this.items)
                {
                    var drAuthorization = this.dtAuthorizations.Where(t => t.ItemName == itemname).FirstOrDefault();
                    if (drAuthorization == null)
                    {
                        drAuthorization = new BuildUserPermissionCacheResult2()
                        {
                            ItemName  = itemname,
                            ValidFrom = null,
                            ValidTo   = null
                        }
                    }
                    ;
                    //string itemName = drAuthorization.ItemName;

                    ManualResetEvent waitHandle = new ManualResetEvent(false);
                    waitHandles.Add(waitHandle);
                    //New Thread Pool
                    ThreadPool.QueueUserWorkItem(new WaitCallback(
                                                     delegate(object o)
                    {
                        IAzManStorage clonedStorage = new SqlAzManStorage(((SqlAzManStorage)this.storage).db.Connection.ConnectionString);
                        int localIndex = (int)((object[])o)[0];
                        ManualResetEvent localWaitHandle          = (ManualResetEvent)((object[])o)[1];
                        BuildUserPermissionCacheResult2 localAuth = (BuildUserPermissionCacheResult2)((object[])o)[2];
                        DateTime now    = (DateTime)((object[])o)[3];
                        string itemName = localAuth.ItemName;
                        try
                        {
                            clonedStorage.OpenConnection();
                            ItemCheckAccessResult result = new ItemCheckAccessResult(itemName);
                            result.ValidFrom             = localAuth.ValidFrom.HasValue ? localAuth.ValidFrom.Value : DateTime.MinValue;
                            result.ValidTo = localAuth.ValidTo.HasValue ? localAuth.ValidTo.Value : DateTime.MaxValue;
                            List <KeyValuePair <string, string> > attributes = null;
                            DateTime validFor = localAuth.ValidFrom.HasValue ? localAuth.ValidFrom.Value : now;
                            if (this.windowsIdentity != null)
                            {
                                if (this.retrieveAttributes)
                                {
                                    result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.windowsIdentity, validFor, false, out attributes, this.contextParameters);
                                }
                                else
                                {
                                    result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.windowsIdentity, validFor, false, this.contextParameters);
                                }
                            }
                            else if (this.dbUser != null)
                            {
                                if (this.retrieveAttributes)
                                {
                                    result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.dbUser, validFor, false, out attributes, this.contextParameters);
                                }
                                else
                                {
                                    result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.dbUser, validFor, false, this.contextParameters);
                                }
                            }
                            result.Attributes = attributes;
                            //Thread safety
                            lock (allResult.SyncRoot)
                            {
                                allResult.Add(localIndex, new object[] { itemName, result });
                            }
                        }
                        catch (Exception ex)
                        {
                            lastException = ex;
                        }
                        finally
                        {
                            clonedStorage.CloseConnection();
                            localWaitHandle.Set();
                        }
                    }), new object[] { index, waitHandle, drAuthorization, globalNow });
                    index++;
                }
                if (lastException != null)
                {
                    throw lastException;
                }
                int count = index;
                //Wait for all threads: http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic28609.aspx
                if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                {
                    // WaitAll for multiple handles on an STA thread is not supported.
                    // ...so wait on each handle individually.
                    foreach (ManualResetEvent myWaitHandle in waitHandles)
                    {
                        myWaitHandle.WaitOne();
                    }
                }
                else
                {
                    WaitHandle.WaitAll(waitHandles.ToArray());
                }
                //Extends all results
                index = 0;
                for (int i = 0; i < count; i++)
                {
                    object[] values              = (object[])allResult[index++];
                    string   itemName            = (string)((object[])values)[0];
                    ItemCheckAccessResult result = (ItemCheckAccessResult)((object[])values)[1];
                    results.Add(result);
                    this.extendResultToMembers(itemName, result, results);
                }
                this.checkAccessTimeSlice = results.ToArray();
            }
            finally
            {
                this.storage.CloseConnection();
            }
        }
        private void buildApplicationCacheMultiThread()
        {
            try
            {
                DateTime globalNow = DateTime.Now;
                this.storage.OpenConnection();
                this.collectPermissionData();
                List<ItemCheckAccessResult> results = new List<ItemCheckAccessResult>();
                IAzManSid sid = this.windowsIdentity != null ? new SqlAzManSID(this.windowsIdentity.User) : this.dbUser.CustomSid;
                List<ManualResetEvent> waitHandles = new List<ManualResetEvent>();
                Hashtable allResult = new Hashtable();
                int index = 0;
                Exception lastException = null;

                foreach (String itemname in this.items)
                {
                    var drAuthorization = this.dtAuthorizations.Where(t => t.ItemName == itemname).FirstOrDefault();
                    if (drAuthorization == null)
                        drAuthorization = new BuildUserPermissionCacheResult2()
                        {
                            ItemName = itemname,
                            ValidFrom = null,
                            ValidTo = null
                        };
                    //string itemName = drAuthorization.ItemName;

                    ManualResetEvent waitHandle = new ManualResetEvent(false);
                    waitHandles.Add(waitHandle);
                    //New Thread Pool
                    ThreadPool.QueueUserWorkItem(new WaitCallback(
                        delegate(object o)
                        {
                            IAzManStorage clonedStorage = new SqlAzManStorage(((SqlAzManStorage)this.storage).db.Connection.ConnectionString);
                            int localIndex = (int)((object[])o)[0];
                            ManualResetEvent localWaitHandle = (ManualResetEvent)((object[])o)[1];
                            BuildUserPermissionCacheResult2 localAuth = (BuildUserPermissionCacheResult2)((object[])o)[2];
                            DateTime now = (DateTime)((object[])o)[3];
                            string itemName = localAuth.ItemName;
                            try
                            {
                                clonedStorage.OpenConnection();
                                ItemCheckAccessResult result = new ItemCheckAccessResult(itemName);
                                result.ValidFrom = localAuth.ValidFrom.HasValue ? localAuth.ValidFrom.Value : DateTime.MinValue;
                                result.ValidTo = localAuth.ValidTo.HasValue ? localAuth.ValidTo.Value : DateTime.MaxValue;
                                List<KeyValuePair<string, string>> attributes = null;
                                DateTime validFor = localAuth.ValidFrom.HasValue ? localAuth.ValidFrom.Value : now;
                                if (this.windowsIdentity != null)
                                {
                                    if (this.retrieveAttributes)
                                        result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.windowsIdentity, validFor, false, out attributes, this.contextParameters);
                                    else
                                        result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.windowsIdentity, validFor, false, this.contextParameters);

                                }
                                else if (this.dbUser != null)
                                {
                                    if (this.retrieveAttributes)
                                        result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.dbUser, validFor, false, out attributes, this.contextParameters);
                                    else
                                        result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.dbUser, validFor, false, this.contextParameters);
                                }
                                result.Attributes = attributes;
                                //Thread safety
                                lock (allResult.SyncRoot)
                                {
                                    allResult.Add(localIndex, new object[] { itemName, result });
                                }
                            }
                            catch (Exception ex)
                            {
                                lastException = ex;
                            }
                            finally
                            {
                                clonedStorage.CloseConnection();
                                localWaitHandle.Set();
                            }
                        }), new object[] { index, waitHandle, drAuthorization, globalNow });
                    index++;
                }
                if (lastException != null)
                    throw lastException;
                int count = index;
                //Wait for all threads: http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic28609.aspx
                if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                {
                    // WaitAll for multiple handles on an STA thread is not supported.
                    // ...so wait on each handle individually.
                    foreach (ManualResetEvent myWaitHandle in waitHandles)
                    {
                        myWaitHandle.WaitOne();
                    }
                }
                else
                {
                    WaitHandle.WaitAll(waitHandles.ToArray());
                }
                //Extends all results
                index = 0;
                for (int i = 0; i < count; i++)
                {
                    object[] values = (object[])allResult[index++];
                    string itemName = (string)((object[])values)[0];
                    ItemCheckAccessResult result = (ItemCheckAccessResult)((object[])values)[1];
                    results.Add(result);
                    this.extendResultToMembers(itemName, result, results);
                }
                this.checkAccessTimeSlice = results.ToArray();
            }
            finally
            {
                this.storage.CloseConnection();
            }
        }