private void OnEnter(object source, EventArgs eventArgs)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            if (context.SkipAuthorization)
            {
                if ((context.User == null) || !context.User.Identity.IsAuthenticated)
                {
                    PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
                }
            }
            else
            {
                AuthorizationSection authorization = RuntimeConfig.GetConfig(context).Authorization;
                if (!authorization.EveryoneAllowed && !authorization.IsUserAllowed(context.User, context.Request.RequestType))
                {
                    ReportUrlAuthorizationFailure(context, this);
                }
                else
                {
                    if ((context.User == null) || !context.User.Identity.IsAuthenticated)
                    {
                        PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
                    }
                    WebBaseEvent.RaiseSystemEvent(this, 0xfa3);
                }
            }
        }
Esempio n. 2
0
        void OnAuthorizeRequest(object sender, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)sender;
            HttpContext     context = app.Context;

            if (context == null || context.SkipAuthorization)
            {
                return;
            }

            HttpRequest req = context.Request;

#if NET_2_0
            AuthorizationSection config = (AuthorizationSection)WebConfigurationManager.GetSection("system.web/authorization", req.Path, context);
#else
            AuthorizationConfig config = (AuthorizationConfig)context.GetConfig("system.web/authorization");
            if (config == null)
            {
                return;
            }
#endif
            if (!config.IsValidUser(context.User, req.HttpMethod))
            {
                HttpException e        = new HttpException(401, "Unauthorized");
                HttpResponse  response = context.Response;

                response.StatusCode = 401;
                response.Write(e.GetHtmlErrorMessage());
                app.CompleteRequest();
            }
        }
        public static bool CheckUrlAccessForPrincipal(string virtualPath, IPrincipal user, string verb)
        {
            if (virtualPath == null)
            {
                throw new ArgumentNullException("virtualPath");
            }
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (verb == null)
            {
                throw new ArgumentNullException("verb");
            }
            verb = verb.Trim();
            VirtualPath path = VirtualPath.Create(virtualPath);

            if (!path.IsWithinAppRoot)
            {
                throw new ArgumentException(System.Web.SR.GetString("Virtual_path_outside_application_not_supported"), "virtualPath");
            }
            if (!s_EnabledDetermined)
            {
                if (!HttpRuntime.UseIntegratedPipeline)
                {
                    HttpModulesSection httpModules = RuntimeConfig.GetConfig().HttpModules;
                    int count = httpModules.Modules.Count;
                    for (int i = 0; i < count; i++)
                    {
                        HttpModuleAction action = httpModules.Modules[i];
                        if (Type.GetType(action.Type, false) == typeof(UrlAuthorizationModule))
                        {
                            s_Enabled = true;
                            break;
                        }
                    }
                }
                else
                {
                    foreach (ModuleConfigurationInfo info in HttpApplication.IntegratedModuleList)
                    {
                        if (Type.GetType(info.Type, false) == typeof(UrlAuthorizationModule))
                        {
                            s_Enabled = true;
                            break;
                        }
                    }
                }
                s_EnabledDetermined = true;
            }
            if (s_Enabled)
            {
                AuthorizationSection authorization = RuntimeConfig.GetConfig(path).Authorization;
                if (!authorization.EveryoneAllowed)
                {
                    return(authorization.IsUserAllowed(user, verb));
                }
            }
            return(true);
        }
Esempio n. 4
0
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        // Module Enter: Get the authorization configuration section
        //    and see if this user is allowed or not
        void OnEnter(Object source, EventArgs eventArgs)
        {
            HttpApplication app;
            HttpContext     context;

            app     = (HttpApplication)source;
            context = app.Context;
            if (context.SkipAuthorization)
            {
                if (context.User == null || !context.User.Identity.IsAuthenticated)
                {
                    PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
                }
                return;
            }

            // Get the authorization config object
            AuthorizationSection settings = RuntimeConfig.GetConfig(context).Authorization;

            // Check if the user is allowed, or the request is for the login page
            if (!settings.EveryoneAllowed && !settings.IsUserAllowed(context.User, context.Request.RequestType))
            {
                ReportUrlAuthorizationFailure(context, this);
            }
            else
            {
                if (context.User == null || !context.User.Identity.IsAuthenticated)
                {
                    PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
                }

                WebBaseEvent.RaiseSystemEvent(this, WebEventCodes.AuditUrlAuthorizationSuccess);
            }
        }
        public void Defaults()
        {
            AuthorizationSection a = new AuthorizationSection();

            Assert.IsNotNull(a.Rules, "A1");
            Assert.AreEqual(0, a.Rules.Count, "A2");
        }
        internal static bool IsUserAllowedToPath(HttpContext context, VirtualPath virtualPath)
        {
            AuthorizationSection authorization = RuntimeConfig.GetConfig(context, virtualPath).Authorization;

            if (!authorization.EveryoneAllowed)
            {
                return(authorization.IsUserAllowed(context.User, context.Request.RequestType));
            }
            return(true);
        }
Esempio n. 7
0
 // add first group of rules
 protected void AddFirstGroupOfRules(AuthorizationSection section, ArrayList rulesArray, int selectedIndex, string upOrDown)
 {
     int adj;
     if (upOrDown == "up") adj = 1;
     else adj = 0;
     for (int x = 0; x < selectedIndex - adj; x++)
     {
         section.Rules.Add((AuthorizationRule)rulesArray[x]);
     }
 }
        /// <summary>
        /// Gets authorization collection for a given site.
        /// </summary>
        /// <param name="siteName">Site's name to get authorization collection for.</param>
        /// <returns>Authorization collection.</returns>
        public AuthorizationRuleCollection GetAuthorizationRuleCollection(string siteName)
        {
            AuthorizationSection        section = (AuthorizationSection)FtpHelper.GetAppHostSection(ServerManager, "system.ftpServer/security/authorization", typeof(AuthorizationSection), ManagementConfigurationPath.CreateSiteConfigurationPath(siteName));
            AuthorizationRuleCollection rules   = section.Rules;

            if (rules == null)
            {
                throw new Exception("ConfigurationError");
            }
            return(rules);
        }
        internal static bool RequestRequiresAuthorization(HttpContext context)
        {
            if (context.SkipAuthorization)
            {
                return(false);
            }
            AuthorizationSection authorization = RuntimeConfig.GetConfig(context).Authorization;

            if (_AnonUser == null)
            {
                _AnonUser = new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[0]);
            }
            return(!authorization.IsUserAllowed(_AnonUser, context.Request.RequestType));
        }
Esempio n. 10
0
 public void AddTheTwoSwappedRules(AuthorizationSection section,
                                   ArrayList rulesArray, int selectedIndex, string upOrDown)
 {
     if (upOrDown == "up")
     {
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex]);
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex - 1]);
     }
     else if (upOrDown == "down")
     {
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex + 1]);
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex]);
     }
 }
Esempio n. 11
0
    public void LoadRulesInNewOrder(AuthorizationSection section,
                                    ArrayList rulesArray, int selectedIndex, string upOrDown)
    {
        /*
         * Dan Clem, 3/17/2007.
         * I hope this is simple enough.
         * Imagine you have five local rules and you click a button to move the middle one.
         * In that scenario, all three of these methods will add rules.
         * If, however, there are only two local rules to start with, then only the middle method will add rules.
         * The first and third methods won't do anything, because their FOR loops will never execute.
         */

        AddFirstGroupOfRules(section, rulesArray, selectedIndex, upOrDown);
        AddTheTwoSwappedRules(section, rulesArray, selectedIndex, upOrDown);
        AddFinalGroupOfRules(section, rulesArray, selectedIndex, upOrDown);
    }
Esempio n. 12
0
        private static void Initialize()
        {
            AuthorizationSection section = System.Configuration.ConfigurationManager.GetSection("Colosoft.Route.Security") as AuthorizationSection;

            if (section != null)
            {
                _providers = new AuthorizationProviderCollection();
                System.Web.Configuration.ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(AuthorizationProvider));
                _providers.SetReadOnly();
                _provider = _providers[section.DefaultProvider.Trim()];
                if (_provider != null)
                {
                    return;
                }
            }
        }
Esempio n. 13
0
        static internal bool RequestRequiresAuthorization(HttpContext context)
        {
            if (context.SkipAuthorization)
            {
                return(false);
            }

            AuthorizationSection settings = RuntimeConfig.GetConfig(context).Authorization;

            // Check if the anonymous user is allowed
            if (_AnonUser == null)
            {
                _AnonUser = new GenericPrincipal(new GenericIdentity(String.Empty, String.Empty), new String[0]);
            }

            return(!settings.IsUserAllowed(_AnonUser, context.Request.RequestType));
        }
Esempio n. 14
0
    public void AddFinalGroupOfRules(AuthorizationSection section,
                                     ArrayList rulesArray, int selectedIndex, string upOrDown)
    {
        int adj;

        if (upOrDown == "up")
        {
            adj = 1;
        }
        else
        {
            adj = 2;
        }
        for (int x = selectedIndex + adj; x < rulesArray.Count; x++)
        {
            section.Rules.Add((AuthorizationRule)rulesArray[x]);
        }
    }
Esempio n. 15
0
    public void MoveRule(object sender, EventArgs e, string upOrDown)
    {
        /*
         * Dan Clem, 3/17/2007
         */
        upOrDown = upOrDown.ToLower();

        if (upOrDown == "up" || upOrDown == "down")
        {
            Button      button        = (Button)sender;
            GridViewRow item          = (GridViewRow)button.Parent.Parent;
            int         selectedIndex = item.RowIndex;
            if ((selectedIndex > 0 && upOrDown == "up") || (upOrDown == "down"))
            {
                string                virtualFolderPath = FolderTree.SelectedValue;
                Configuration         config            = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath);
                SystemWebSectionGroup systemWeb         = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
                AuthorizationSection  section           = (AuthorizationSection)systemWeb.Sections["authorization"];

                // Pull the local rules out of the authorization section, deleting them from same:
                ArrayList rulesArray = PullLocalRulesOutOfAuthorizationSection(section);
                if (upOrDown == "up")
                {
                    LoadRulesInNewOrder(section, rulesArray, selectedIndex, upOrDown);
                }
                else if (upOrDown == "down")
                {
                    if (selectedIndex < rulesArray.Count - 1)
                    {
                        LoadRulesInNewOrder(section, rulesArray, selectedIndex, upOrDown);
                    }
                    else
                    {
                        // DOWN button in last row was pressed. Load the rules array back in without resorting.
                        for (int x = 0; x < rulesArray.Count; x++)
                        {
                            section.Rules.Add((AuthorizationRule)rulesArray[x]);
                        }
                    }
                }
                config.Save();
            }
        }
    }
Esempio n. 16
0
    public void AddRule(AuthorizationRule newRule)
    {
        string                virtualFolderPath = FolderTree.SelectedValue;
        Configuration         config            = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath);
        SystemWebSectionGroup systemWeb         = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
        AuthorizationSection  section           = (AuthorizationSection)systemWeb.Sections["authorization"];

        section.Rules.Add(newRule);
        try
        {
            config.Save();
            RuleCreationError.Visible = false;
        }
        catch (Exception ex)
        {
            RuleCreationError.Visible = true;
            RuleCreationError.Text    = "<div class=\"alert\"><br />An error occurred and the rule was not added. I saw this happen during testing when I attempted to create a rule that the ASP.NET infrastructure realized was redundant. Specifically, I had the rule <i>DENY ALL USERS</i> in one folder, then attempted to add the same rule in a subfolder, which caused ASP.NET to throw an exception.<br /><br />Here's the error message that was thrown just now:<br /><br /><i>" + ex.Message + "</i></div>";
        }
    }
Esempio n. 17
0
        static bool CheckAuth(HttpApplication app, Configuration sc)
        {
            AuthorizationSection ac = sc.GetSection("system.web/authorization") as AuthorizationSection;

            if (ac != null)
            {
                if (!(bool)everyoneallowed.GetValue(ac, null))
                {
                    bool ok = (bool)checkuser.Invoke(ac, new object[] { app.User, app.Request.HttpMethod });
                    if (!ok)
                    {
                        app.Context.Response.StatusCode = 401;
                        app.CompleteRequest();
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 18
0
    public ArrayList PullLocalRulesOutOfAuthorizationSection(AuthorizationSection section)
    {
        // Dan Clem, 3/17/2007.
        // First load the local rules into an ArrayList.

        ArrayList rulesArray = new ArrayList();

        foreach (AuthorizationRule rule in section.Rules)
        {
            if (rule.ElementInformation.IsPresent)
            {
                rulesArray.Add(rule);
            }
        }

        // Next delete the rules from the section.
        foreach (AuthorizationRule rule in rulesArray)
        {
            section.Rules.Remove(rule);
        }
        return(rulesArray);
    }
Esempio n. 19
0
    public void DeleteRule(object sender, EventArgs e)
    {
        /*
         * Dan Clem, 3/16/2007.
         * This is working quite well, however there is a defect that I am not planning to fix right now.
         * If you delete a rule, then attempt to delete another rule from the same folder without
         * refreshing the page, you'll get a page error. The workaround is to re-click the folder in the
         * tree to refresh it, then delete the rule.
         * Don't feel like worrying about this right now.
         *
         * Note: this problem may have been fixed already.
         * I stopped using the session array method for handling things.
         * This may have fixed it. I'll test later.
         */
        Button                button            = (Button)sender;
        GridViewRow           item              = (GridViewRow)button.Parent.Parent;
        string                virtualFolderPath = FolderTree.SelectedValue;
        Configuration         config            = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath);
        SystemWebSectionGroup systemWeb         = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
        AuthorizationSection  section           = (AuthorizationSection)systemWeb.Sections["authorization"];

        section.Rules.RemoveAt(item.RowIndex);
        config.Save();
    }
        static void Main(string[] args)
        {
            // Display title and info.
            Console.WriteLine("ASP.NET Configuration Info");
            Console.WriteLine("Type: CommaDelimitedStringCollection");
            Console.WriteLine();

            // Set the path of the config file.
            string configPath = "/aspnet";

            // Get the Web application configuration object.
            Configuration config =
                WebConfigurationManager.OpenWebConfiguration(configPath);

            // Get the section related object.
            AuthorizationSection configSection =
                (AuthorizationSection)config.GetSection("system.web/authorization");

            // Get the authorization rule collection.
            AuthorizationRuleCollection authorizationRuleCollection =
                configSection.Rules;

            // <Snippet2>
            // Create a CommaDelimitedStringCollection object.
            CommaDelimitedStringCollection myStrCollection =
                new CommaDelimitedStringCollection();

            // </Snippet2>

            for (int i = 0; i < authorizationRuleCollection.Count; i++)
            {
                if (authorizationRuleCollection.Get(i).Action.ToString().ToLower()
                    == "allow")
                {
                    // <Snippet3>
                    // Add values to the CommaDelimitedStringCollection object.
                    myStrCollection.AddRange(
                        authorizationRuleCollection.Get(i).Users.ToString().Split(
                            ",".ToCharArray()));
                    // </Snippet3>
                }
            }

            Console.WriteLine("Allowed Users: {0}",
                              myStrCollection.ToString());

            // <Snippet4>
            // Count the elements in the collection.
            Console.WriteLine("Allowed User Count: {0}",
                              myStrCollection.Count);
            // </Snippet4>

            // <Snippet5>
            // Call the Contains method.
            Console.WriteLine("Contains 'userName1': {0}",
                              myStrCollection.Contains("userName1"));
            // </Snippet5>

            // <Snippet6>
            // Determine the index of an element
            // in the collection.
            Console.WriteLine("IndexOf 'userName0': {0}",
                              myStrCollection.IndexOf("userName0"));
            // </Snippet6>

            // <Snippet7>
            // Call IsModified.
            Console.WriteLine("IsModified: {0}",
                              myStrCollection.IsModified);
            // </Snippet7>

            // <Snippet8>
            // Call IsReadyOnly.
            Console.WriteLine("IsReadOnly: {0}",
                              myStrCollection.IsReadOnly);
            // </Snippet8>

            Console.WriteLine();
            Console.WriteLine("Add a user name to the collection.");
            // <Snippet9>
            // Insert a new element in the collection.
            myStrCollection.Insert(myStrCollection.Count, "userNameX");
            // </Snippet9>

            Console.WriteLine("Collection Value: {0}",
                              myStrCollection.ToString());

            Console.WriteLine();
            Console.WriteLine("Remove a user name from the collection.");
            // <Snippet10>
            // Remove an element of the collection.
            myStrCollection.Remove("userNameX");
            // </Snippet10>

            Console.WriteLine("Collection Value: {0}",
                              myStrCollection.ToString());

            // Display and wait
            Console.ReadLine();
        }
Esempio n. 21
0
    // use local rules out of authorization section
    protected ArrayList PullLocalRulesOutOfAuthorizationSection(AuthorizationSection section)
    {
        // First load the local rules into an ArrayList.
        ArrayList rulesArray = new ArrayList();
        foreach (AuthorizationRule rule in section.Rules)
        {
            if (rule.ElementInformation.IsPresent)
            {
                rulesArray.Add(rule);
            }
        }

        // Next delete the rules from the section.
        foreach (AuthorizationRule rule in rulesArray)
        {
            section.Rules.Remove(rule);
        }
        return rulesArray;
    }
Esempio n. 22
0
        /// <summary>
        /// Action after clicking login button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Login_Click(object sender, EventArgs e)
        {
            this.ErrorInfo.Text = String.Empty;
            bool persistent = false;
            // Authorization using portal's membership provider when STS authentication is inactive.
            AuthorizationSection section = (AuthorizationSection)WebConfigurationManager.GetSection("system.web/authorization");

            foreach (System.Web.Configuration.AuthorizationRule entry in section.Rules)
            {
                if (entry.Action == System.Web.Configuration.AuthorizationRuleAction.Allow && entry.Users.Contains("*"))
                {
                    try
                    {
                        if (Membership.ValidateUser(UsernameTextBox.Text, PasswordTextBox.Text))
                        {
                            if (RememberCheckbox.Checked)
                            {
                                persistent = true;
                            }
                            System.Web.Security.FormsAuthentication.RedirectFromLoginPage(UsernameTextBox.Text, persistent);
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        this.ErrorInfo.Text = GetLocalResourceObject("AuthenticationError.Text").ToString();
                        return;
                    }
                }
            }

            SecurityToken Token = null;

            try
            {
                Token = SecurityTokenStore.GetTokenFromUsername(UsernameTextBox.Text, PasswordTextBox.Text);
                if (Token != null)
                {
                    SecurityTokenStore.StoreToken(Token, UsernameTextBox.Text);
                    if (RememberCheckbox.Checked)
                    {
                        persistent = true;
                    }
                    System.Web.Security.FormsAuthentication.RedirectFromLoginPage(UsernameTextBox.Text, persistent);
                }
            }
            catch (Exception ex)
            {
                this.ErrorInfo.Text = GetLocalResourceObject("AuthenticationError.Text").ToString();
                if (ex.InnerException != null)
                {
                    switch (ex.InnerException.Message)
                    {
                    case STSConstants.InvalidUsernameOrPassword:
                        this.ErrorInfo.Text = GetLocalResourceObject("IncorrectCredentials.Text").ToString();
                        break;

                    case STSConstants.PasswordExpired:
                        this.ErrorInfo.Text = GetLocalResourceObject("AuthorizationError.Text").ToString();
                        break;

                    case STSConstants.AccountSuspended:
                        this.ErrorInfo.Text = GetLocalResourceObject("AccountSuspended.Text").ToString();
                        break;

                    case STSConstants.ID3242:
                        this.ErrorInfo.Text = GetLocalResourceObject("IncorrectCredentials.Text").ToString();
                        break;

                    default:
                        this.ErrorInfo.Text = GetLocalResourceObject("AuthenticationError.Text").ToString();
                        break;
                    }
                }
            }
        }
Esempio n. 23
0
        public static void Main()
        {
            // <Snippet1>
            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");
            // </Snippet1>

            // <Snippet2>
            // Get the section.
            AuthorizationSection authorizationSection =
                (AuthorizationSection)configuration.GetSection(
                    "system.web/authorization");
            // </Snippet2>

            // <Snippet3>
            // Get the authorization rule collection.
            AuthorizationRuleCollection authorizationRuleCollection =
                authorizationSection.Rules;
            // </Snippet3>

            // <Snippet4>
            // Create an authorization rule object.
            AuthorizationRuleAction action =
                AuthorizationRuleAction.Deny;
            AuthorizationRule authorizationRule =
                new System.Web.Configuration.AuthorizationRule(action);
            // </Snippet4>


            // <Snippet5>
            // Create a new 'AuthorizationSection' object.
            AuthorizationSection newauthorizationSection =
                new System.Web.Configuration.AuthorizationSection();

            // </Snippet5>


            // <Snippet6>
            // Using the AuthorizationRuleCollection Add method.

            // Set the action property.
            authorizationRule.Action =
                AuthorizationRuleAction.Allow;
            // Define the new rule to add to the collection.
            authorizationRule.Users.Add("userName");
            authorizationRule.Roles.Add("admin");
            authorizationRule.Verbs.Add("POST");

            // Add the new rule to the collection.
            authorizationSection.Rules.Add(authorizationRule);
            // </Snippet6>

            // <Snippet7>
            // Using the AuthorizationRuleCollection Clear method.
            authorizationSection.Rules.Clear();
            // </Snippet7>

            // <Snippet8>
            // Using the AuthorizationRuleCollection RemoveAt method.
            authorizationRuleCollection.RemoveAt(0);
            // </Snippet8>

            // <Snippet9>
            // Get the rule collection index.
            System.Int32 ruleIndex =
                authorizationSection.Rules.IndexOf(authorizationRule);
            // </Snippet9>

            // <Snippet10>
            // Remove the rule from the collection.
            authorizationSection.Rules.Remove(authorizationRule);

            // </Snippet10>

            // <Snippet11>
            // Using the AuthorizationRuleCollection Set method.

            // Define the rule to add to the collection.

            // Define the collection index.
            System.Int32 rIndex = 0;

            // Set the rule in the collection.
            authorizationRuleCollection.Set(rIndex,
                                            authorizationRule);
            // </Snippet11>


            // <Snippet12>
            // Show how to access the Rules elements.
            StringBuilder rules = new StringBuilder();

            for (System.Int32 i = 0;
                 i < authorizationSection.Rules.Count - 1; i++)
            {
                rules.Append("Action: " +
                             authorizationSection.Rules[i].Action.ToString());

                // Get the Verbs.
                System.Int32 verbsCount =
                    authorizationSection.Rules[i].Verbs.Count;
                for (System.Int32 v = 0; v < verbsCount; v++)
                {
                    rules.AppendLine(
                        authorizationSection.Rules[i].Verbs[v]);
                }

                // Get the Roles.
                System.Int32 rolesCount =
                    authorizationSection.Rules[i].Roles.Count;
                for (System.Int32 r = 0; r < rolesCount; r++)
                {
                    rules.AppendLine(authorizationSection.Rules[i].Roles[r]);
                }

                // Get the Users.
                System.Int32 usersCount =
                    authorizationSection.Rules[i].Users.Count;
                for (System.Int32 u = 0; u < usersCount; u++)
                {
                    rules.AppendLine(authorizationSection.Rules[i].Users[u]);
                }
            }

            // </Snippet12>

            // <Snippet13>
            // Using the AuthorizationRuleCollection Get method.
            AuthorizationRule authRule =
                authorizationRuleCollection.Get(0);
            // </Snippet13>
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            string inputStr = String.Empty;
            string option   = String.Empty;

            // Define a regular expression to allow only
            // alphanumeric inputs that are at most 20 character
            // long. For instance "/iii:".
            Regex rex = new Regex(@"[^\/w]{1,20}:");

            // Parse the user's input.
            if (args.Length < 1)
            {
                // No option entered.
                Console.Write("Input parameter missing.");
                return;
            }
            else
            {
                // Get the user's option.
                inputStr = args[0].ToLower();
                if (!(rex.Match(inputStr)).Success)
                {
                    // Wrong option format used.
                    Console.Write("Input parameter format not allowed.");
                    return;
                }
            }

            // <Snippet1>

            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");

            // Get the <system.web> group.
            SystemWebSectionGroup systemWeb =
                (SystemWebSectionGroup)configuration.GetSectionGroup("system.web");

            // </Snippet1>


            try
            {
                switch (inputStr)
                {
                case "/anonymous:":
                    // <Snippet2>
                    // Get the anonymousIdentification section.
                    AnonymousIdentificationSection
                        anonymousIdentification =
                        systemWeb.AnonymousIdentification;
                    // Read section information.
                    info =
                        anonymousIdentification.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet2>

                    Console.Write(msg);
                    break;

                case "/authentication:":

                    // <Snippet3>
                    // Get the authentication section.
                    AuthenticationSection authentication =
                        systemWeb.Authentication;
                    // Read section information.
                    info =
                        authentication.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet3>

                    Console.Write(msg);
                    break;

                case "/authorization:":

                    // <Snippet4>
                    // Get the authorization section.
                    AuthorizationSection authorization =
                        systemWeb.Authorization;
                    // Read section information.
                    info =
                        authorization.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet4>

                    Console.Write(msg);
                    break;

                case "/compilation:":

                    // <Snippet5>
                    // Get the compilation section.
                    CompilationSection compilation =
                        systemWeb.Compilation;
                    // Read section information.
                    info =
                        compilation.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet5>

                    Console.Write(msg);
                    break;


                case "/customerrors:":

                    // <Snippet6>
                    // Get the customerrors section.
                    CustomErrorsSection customerrors =
                        systemWeb.CustomErrors;
                    // Read section information.
                    info =
                        customerrors.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet6>

                    Console.Write(msg);
                    break;

                case "/globalization:":

                    // <Snippet7>
                    // Get the globalization section.
                    GlobalizationSection globalization =
                        systemWeb.Globalization;
                    // Read section information.
                    info =
                        globalization.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet7>

                    Console.Write(msg);
                    break;

                case "/httpcookies:":
                    // <Snippet8>
                    // Get the httpCookies section.
                    HttpCookiesSection httpCookies =
                        systemWeb.HttpCookies;
                    // Read section information.
                    info =
                        httpCookies.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet8>

                    Console.Write(msg);
                    break;

                case "/httphandlers:":

                    // <Snippet9>
                    // Get the httpHandlers section.
                    HttpHandlersSection httpHandlers =
                        systemWeb.HttpHandlers;
                    // Read section information.
                    info =
                        httpHandlers.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet9>

                    Console.Write(msg);
                    break;

                case "/httpmodules:":

                    // <Snippet10>
                    // Get the httpModules section.
                    HttpModulesSection httpModules =
                        systemWeb.HttpModules;
                    // Read section information.
                    info =
                        httpModules.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet10>

                    Console.Write(msg);
                    break;

                case "/httpruntime:":

                    // <Snippet11>
                    // Get the httpRuntime section.
                    HttpRuntimeSection httpRuntime =
                        systemWeb.HttpRuntime;
                    // Read section information.
                    info =
                        httpRuntime.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet11>

                    Console.Write(msg);
                    break;

                case "/identity:":

                    // <Snippet12>
                    // Get the identity section.
                    IdentitySection identity =
                        systemWeb.Identity;
                    // Read section information.
                    info =
                        identity.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet12>

                    Console.Write(msg);
                    break;

                case "/machinekey:":

                    // <Snippet13>
                    // Get the machineKey section.
                    MachineKeySection machineKey =
                        systemWeb.MachineKey;
                    // Read section information.
                    info =
                        machineKey.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet13>

                    Console.Write(msg);
                    break;

                case "/membership:":
                    // <Snippet14>
                    // Get the membership section.
                    MembershipSection membership =
                        systemWeb.Membership;
                    // Read section information.
                    info =
                        membership.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet14>

                    Console.Write(msg);
                    break;

                case "/pages:":
                    // <Snippet15>
                    // Get the pages section.
                    PagesSection pages =
                        systemWeb.Pages;
                    // Read section information.
                    info =
                        pages.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet15>

                    Console.Write(msg);
                    break;

                case "/processModel:":
                    // <Snippet16>
                    // Get the processModel section.
                    ProcessModelSection processModel =
                        systemWeb.ProcessModel;
                    // Read section information.
                    info =
                        processModel.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet16>

                    Console.Write(msg);
                    break;

                case "/profile:":
                    // <Snippet17>
                    // Get the profile section.
                    ProfileSection profile =
                        systemWeb.Profile;
                    // Read section information.
                    info =
                        profile.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet17>

                    Console.Write(msg);
                    break;

                case "/roleManager:":
                    // <Snippet18>
                    // Get the roleManager section.
                    RoleManagerSection roleManager =
                        systemWeb.RoleManager;
                    // Read section information.
                    info =
                        roleManager.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet18>

                    Console.Write(msg);
                    break;

                case "/securityPolicy:":
                    // <Snippet19>
                    // Get the securityPolicy section.
                    SecurityPolicySection securityPolicy =
                        systemWeb.SecurityPolicy;
                    // Read section information.
                    info =
                        securityPolicy.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet19>

                    Console.Write(msg);
                    break;

                case "/sessionState:":
                    // <Snippet20>
                    // Get the sessionState section.
                    SessionStateSection sessionState =
                        systemWeb.SessionState;
                    // Read section information.
                    info =
                        sessionState.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet20>

                    Console.Write(msg);
                    break;

                case "/sitemap:":
                    // <Snippet21>
                    // Get the siteMap section.
                    SiteMapSection siteMap =
                        systemWeb.SiteMap;
                    // Read section information.
                    info =
                        siteMap.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet21>

                    Console.Write(msg);
                    break;

                case "/trace:":
                    // <Snippet22>
                    // Get the trace section.
                    TraceSection trace =
                        systemWeb.Trace;
                    // Read section information.
                    info =
                        trace.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet22>

                    Console.Write(msg);
                    break;

                case "/trust:":
                    // <Snippet23>
                    // Get the trust section.
                    TrustSection trust =
                        systemWeb.Trust;
                    // Read section information.
                    info =
                        trust.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet23>

                    Console.Write(msg);
                    break;

                case "/browserCaps:":
                    // <Snippet24>
                    // Get the browserCaps section.
                    DefaultSection browserCaps =
                        systemWeb.BrowserCaps;
                    // Read section information.
                    info =
                        browserCaps.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet24>

                    Console.Write(msg);
                    break;

                case "/clientTarget:":
                    // <Snippet25>
                    // Get the clientTarget section.
                    ClientTargetSection clientTarget =
                        systemWeb.ClientTarget;
                    // Read section information.
                    info =
                        clientTarget.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet25>

                    Console.Write(msg);
                    break;


                case "/deployment:":
                    // <Snippet26>
                    // Get the deployment section.
                    DeploymentSection deployment =
                        systemWeb.Deployment;
                    // Read section information.
                    info =
                        deployment.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet26>

                    Console.Write(msg);
                    break;


                case "/deviceFilters:":
                    // <Snippet27>
                    // Get the deviceFilters section.
                    DefaultSection deviceFilters =
                        systemWeb.DeviceFilters;
                    // Read section information.
                    info =
                        deviceFilters.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet27>

                    Console.Write(msg);
                    break;

                case "/healthMonitoring:":
                    // <Snippet28>
                    // Get the healthMonitoring section.
                    HealthMonitoringSection healthMonitoring =
                        systemWeb.HealthMonitoring;
                    // Read section information.
                    info =
                        healthMonitoring.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet28>

                    Console.Write(msg);
                    break;

                case "/hostingEnvironment:":
                    // <Snippet29>
                    // Get the hostingEnvironment section.
                    HostingEnvironmentSection hostingEnvironment =
                        systemWeb.HostingEnvironment;
                    // Read section information.
                    info =
                        hostingEnvironment.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet29>

                    Console.Write(msg);
                    break;

                case "/mobileControls:":
                    // <Snippet30>
                    // Get the mobileControls section.
                    ConfigurationSection mobileControls =
                        systemWeb.MobileControls;
                    // Read section information.
                    info =
                        mobileControls.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet30>

                    Console.Write(msg);
                    break;

                case "/protocols:":
                    // <Snippet31>
                    // Get the protocols section.
                    DefaultSection protocols =
                        systemWeb.Protocols;
                    // Read section information.
                    info =
                        protocols.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet31>

                    Console.Write(msg);
                    break;

                case "/urlMappings:":
                    // <Snippet32>
                    // Get the urlMappings section.
                    UrlMappingsSection urlMappings =
                        systemWeb.UrlMappings;
                    // Read section information.
                    info =
                        urlMappings.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet32>

                    Console.Write(msg);
                    break;

                case "/webControls:":
                    // <Snippet33>
                    // Get the webControls section.
                    WebControlsSection webControls =
                        systemWeb.WebControls;
                    // Read section information.
                    info =
                        webControls.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet33>

                    Console.Write(msg);
                    break;

                case "/webParts:":
                    // <Snippet34>
                    // Get the webParts section.
                    WebPartsSection webParts =
                        systemWeb.WebParts;
                    // Read section information.
                    info =
                        webParts.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet34>

                    Console.Write(msg);
                    break;

                case "/webServices:":
                    // <Snippet35>
                    // Get the webServices section.
                    WebServicesSection webServices =
                        systemWeb.WebServices;
                    // Read section information.
                    info =
                        webServices.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet35>

                    Console.Write(msg);
                    break;

                case "/XhtmlConformance:":
                    // <Snippet36>
                    // Get the xhtmlConformance section.
                    XhtmlConformanceSection xhtmlConformance =
                        systemWeb.XhtmlConformance;
                    // Read section information.
                    info =
                        xhtmlConformance.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();

                    msg = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet36>

                    Console.Write(msg);
                    break;


                case "/all:":
                    StringBuilder             allSections    = new StringBuilder();
                    ConfigurationSectionGroup systemWebGroup =
                        configuration.GetSectionGroup("system.web");
                    int i = 0;
                    foreach (ConfigurationSection section in
                             systemWebGroup.Sections)
                    {
                        i       += 1;
                        info     = section.SectionInformation;
                        name     = info.SectionName;
                        type     = info.Type;
                        declared = info.IsDeclared.ToString();
                        if (i < 10)
                        {
                            msg = String.Format(
                                "{0})Name:   {1}\nDeclared: {2}\nType:     {3}\n",
                                i.ToString(), name, declared, type);
                        }
                        else
                        {
                            msg = String.Format(
                                "{0})Name:  {1}\nDeclared: {2}\nType:     {3}\n",
                                i.ToString(), name, declared, type);
                        }
                        allSections.AppendLine(msg);
                    }

                    // Console.WriteLine(systemWebGroup.Name);
                    // Console.WriteLine(systemWebGroup.SectionGroupName);

                    Console.Write(allSections.ToString());
                    break;

                default:
                    // Option is not allowed..
                    Console.Write("Input not allowed.");
                    break;
                }
            }
            catch (ArgumentException e)
            {
                // Never display this. Use it for
                // debugging purposes.
                msg = e.ToString();
            }
        }
Esempio n. 25
0
        public static bool CheckUrlAccessForPrincipal(String virtualPath, IPrincipal user, string verb)
        {
            if (virtualPath == null)
            {
                throw new ArgumentNullException("virtualPath");
            }
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (verb == null)
            {
                throw new ArgumentNullException("verb");
            }
            verb = verb.Trim();

            VirtualPath vPath = VirtualPath.Create(virtualPath);

            if (!vPath.IsWithinAppRoot)
            {
                throw new ArgumentException(SR.GetString(SR.Virtual_path_outside_application_not_supported), "virtualPath");
            }

            if (!s_EnabledDetermined)
            {
                if (!HttpRuntime.UseIntegratedPipeline)
                {
                    HttpModulesSection modulesSection = RuntimeConfig.GetConfig().HttpModules;
                    int len = modulesSection.Modules.Count;
                    for (int iter = 0; iter < len; iter++)
                    {
                        HttpModuleAction module = modulesSection.Modules[iter];
                        if (Type.GetType(module.Type, false) == typeof(UrlAuthorizationModule))
                        {
                            s_Enabled = true;
                            break;
                        }
                    }
                }
                else
                {
                    List <ModuleConfigurationInfo> modules = HttpApplication.IntegratedModuleList;
                    foreach (ModuleConfigurationInfo mod in modules)
                    {
                        if (Type.GetType(mod.Type, false) == typeof(UrlAuthorizationModule))
                        {
                            s_Enabled = true;
                            break;
                        }
                    }
                }
                s_EnabledDetermined = true;
            }
            if (!s_Enabled)
            {
                return(true);
            }
            AuthorizationSection settings = RuntimeConfig.GetConfig(vPath).Authorization;

            // Check if the user is allowed, or the request is for the login page
            return(settings.EveryoneAllowed || settings.IsUserAllowed(user, verb));
        }
Esempio n. 26
0
        internal static bool IsUserAllowedToPath(HttpContext context, VirtualPath virtualPath)
        {
            AuthorizationSection settings = RuntimeConfig.GetConfig(context, virtualPath).Authorization;

            return(settings.EveryoneAllowed || settings.IsUserAllowed(context.User, context.Request.RequestType));
        }
Esempio n. 27
0
 public GeneralSettings()
 {
     AuthorizationSection = new AuthorizationSection();
     SignalRSettings      = new SignalRSettings();
 }
        public static bool CheckUrlAccessForPrincipal(string virtualPath, IPrincipal user, string verb)
        {
            AuthorizationSection config = (AuthorizationSection)WebConfigurationManager.GetSection("system.web/authorization", virtualPath);

            return(config == null ? true : config.IsValidUser(user, verb));
        }
Esempio n. 29
0
 // load rules in new order
 protected void LoadRulesInNewOrder(AuthorizationSection section, ArrayList rulesArray, int selectedIndex, string upOrDown)
 {
     AddFirstGroupOfRules(section, rulesArray, selectedIndex, upOrDown);
     AddTheTwoSwappedRules(section, rulesArray, selectedIndex, upOrDown);
     AddFinalGroupOfRules(section, rulesArray, selectedIndex, upOrDown);
 }
Esempio n. 30
0
        public virtual bool IsAccessibleToUser(HttpContext context, SiteMapNode node)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            if (!SecurityTrimmingEnabled)
            {
                return(true);
            }

            /* The node is accessible (according to msdn2) if:
             *
             * 1. The Roles exists on node and the current user is in at least one of the specified roles.
             *
             * 2. The current thread has an associated WindowsIdentity that has file access to the requested URL and
             * the URL is located within the directory structure for the application.
             *
             * 3. The current user is authorized specifically for the requested URL in the authorization element for
             * the current application and the URL is located within the directory structure for the application.
             */

            /* 1. */
            IList roles = node.Roles;

            if (roles != null && roles.Count > 0)
            {
                foreach (string rolename in roles)
                {
                    if (rolename == "*" || context.User.IsInRole(rolename))
                    {
                        return(true);
                    }
                }
            }

            /* 2. */
            /* XXX */

            /* 3. */
            string url = node.Url;

            if (!String.IsNullOrEmpty(url))
            {
                // TODO check url is located within the current application

                if (VirtualPathUtility.IsAppRelative(url) || !VirtualPathUtility.IsAbsolute(url))
                {
                    url = VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), url);
                }

                AuthorizationSection config = (AuthorizationSection)WebConfigurationManager.GetSection(
                    "system.web/authorization",
                    url);
                if (config != null)
                {
                    return(config.IsValidUser(context.User, context.Request.HttpMethod));
                }
            }

            return(false);
        }
Esempio n. 31
0
 public SecurityModelMock(AuthorizationSection authorizationSection)
 {
     _AuthorizationSection = authorizationSection;
 }
Esempio n. 32
0
        /// <summary>
        /// 验证用户是否通过登录验证
        /// </summary>
        /// <param name="context"></param>
        private static void CheckUserLogin(HttpContext context)
        {
            bool flag = true;

            if (!context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith("ajax.aspx", StringComparison.OrdinalIgnoreCase) && !context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith("login.aspx", StringComparison.OrdinalIgnoreCase))
            {
                //配置WEB应用程序授权
                AuthorizationSection section = (AuthorizationSection)context.GetSection("system.web/authorization");
                if (((section.Rules.Count > 0) && (section.Rules[0].Action == AuthorizationRuleAction.Allow)) && section.Rules[0].Users.Contains("*"))
                {
                    flag = false;
                }
            }
            if (flag && context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
            {
                //如果用户的验证代号通过
                if (PEContext.Current.User.Identity.IsAuthenticated)
                {
                    bool     flag2    = false;
                    UserInfo userInfo = PEContext.Current.User.UserInfo;
                    if (userInfo.Status != UserStatus.None)
                    {
                        Utility.WriteUserErrMsg(Utility.GetGlobalErrorString("UserIsNotApprove"), "~/Default.aspx");
                    }
                    if (!SiteConfig.UserConfig.EnableMultiLogOn && (PEContext.Current.User.LastPassword != userInfo.LastPassword))
                    {
                        if (context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith("ajax.aspx", StringComparison.OrdinalIgnoreCase))
                        {
                            context.Items["err"] = "err";
                            context.Server.Transfer("~/ajax.aspx");
                        }
                        else
                        {
                            Utility.WriteUserErrMsg(Utility.GetGlobalErrorString("MultiUserLoginSystem"), "");
                        }
                    }
                    if (SiteConfig.UserConfig.PresentExpPerLogOn > 0.0)
                    {
                        bool flag3 = false;
                        if (!userInfo.LastPresentTime.HasValue)
                        {
                            flag3 = true;
                        }
                        else
                        {
                            TimeSpan span = (TimeSpan)(DateTime.Now - userInfo.LastPresentTime.Value);
                            if (span.TotalDays >= 1.0)
                            {
                                flag3 = true;
                            }
                        }
                        if (flag3)
                        {
                            userInfo.UserExp        += (int)SiteConfig.UserConfig.PresentExpPerLogOn;
                            userInfo.LastPresentTime = new DateTime?(DateTime.Now);
                            flag2 = true;
                        }
                    }
                    if ((context.Session != null) && (context.Session["UserName"] == null))
                    {
                        userInfo.LogOnTimes++;
                        userInfo.LastLogOnTime = new DateTime?(DateTime.Now);
                        userInfo.LastLogOnIP   = PEContext.Current.UserHostAddress;
                        flag2 = true;
                        context.Session.Add("UserName", PEContext.Current.User.UserName);
                    }
                    if (!userInfo.LastLogOnTime.HasValue)
                    {
                        userInfo.LastLogOnTime = new DateTime?(DateTime.Now);
                    }
                    if (flag2)
                    {
                        Users.Update(userInfo);
                    }
                }
            }
            else if (PEContext.Current.User.Identity.IsAuthenticated && (PEContext.Current.User.UserInfo.Status != UserStatus.None))
            {
                UserPrincipal principal = new UserPrincipal(new AnonymousAuthenticateIdentity());
                principal.UserInfo                    = new UserInfo(true);
                principal.UserInfo.GroupId            = -2;
                principal.UserInfo.IsInheritGroupRole = true;
                PEContext.Current.User                = principal;
                GenericPrincipal principal2 = new GenericPrincipal(new NoAuthenticateIdentity(), null);
                context.User = principal2;
                FormsAuthentication.SignOut();
            }
        }
Esempio n. 33
0
 // add two swapped rules
 protected void AddTheTwoSwappedRules(AuthorizationSection section, ArrayList rulesArray, int selectedIndex, string upOrDown)
 {
     if (upOrDown == "up")
     {
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex]);
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex - 1]);
     }
     else if (upOrDown == "down")
     {
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex + 1]);
         section.Rules.Add((AuthorizationRule)rulesArray[selectedIndex]);
     }
 }