Here you will find .Net source code, for ASP.Net, WinForms, WCF, Unit Testing, Security and more...
If you find this code useful, please visit our sponsers who help keep this site running.
Tip: Turn off line numbers when using Copy and Paste.
1using System; 2using System.Collections.Specialized; 3using System.Configuration; 4using System.Security.Principal; 5using System.Threading; 6using System.Web.Configuration; 7 8namespace Enterprise.Security 9{ 10 /// <!-- 11 /// Code Courtesy Of http://www.purecoding.net 12 /// Permissions : Free for general use 13 /// Keywords: Security, Identity, c#, .Net, Aspnet. 14 /// Filename: ApplicationSecurity.cs 15 /// --> 16 17 #region Role Enumeration 18 19 /// <summary> 20 /// This enum defines the application level roles. Each one will be mapped to 21 /// 1 or more security group(s) on the network. <see cref="ApplicationSecurity"/> for more information. 22 /// </summary> 23 [Flags] 24 public enum ApplicationRole 25 { 26 Role_User = 1, 27 Role_Editor = 2 28 //Role_Administrator = 4 29 /* Additional Roles and bit flags 30 * Role_ = 4 31 * Role_ = 8 32 * Role_ = 16 33 * Role_ = 32 34 */ 35 36 } 37 38 #endregion 39 40 /// <summary> 41 /// This class implements a Role Based security model for use in ASP.Net 2.0 42 /// The Roles are defined in the <see cref="ApplicationRole"/> enum. The name 43 /// of each enum item must also exist in the web.config. 44 /// The web.config contains a section that is used to map the ApplicationRole to a 45 /// real security group on the network or local computer. 46 /// Usage (Single Role): if(IsInRole(Role_Editor)) { //Permission granted... } 47 /// Usage (Multiple Roles): if(IsInAnyRole(Role_Administrator | Role_Editor)) { //Permission granted... } 48 /// Usage (Multiple Roles): if(IsInAllRoles(Role_Administrator | Role_Editor)) { //Permission granted... } 49 /// </summary> 50 /// <remarks>You can specify multiple domain or local security 51 /// groups by using a semi colon seperated list.</remarks> 52 // Note: In the web.config you need the following: 53 //<configuration> 54 //<configSections> 55 // <section 56 // name="securityRoleMappings" 57 // type="System.Configuration.AppSettingsSection, 58 // System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 59 // restartOnExternalChanges="true" 60 // requirePermission="false" /> 61 //</configSections> 62 //<securityRoleMappings> 63 // <add key="Role_Editor" value="MyDomain\ABC-Editors;MyDomain\Admins;" /> 64 // <add key="Role_User" value="MyDomain\ABC-Users" /> 65 //</securityRoleMappings> 66 public sealed class ApplicationSecurity 67 { 68 #region private constants and constructor 69 70 private static readonly string _ConfigSectionName = "securityRoleMappings"; 71 72 private ApplicationSecurity() 73 { 74 } 75 76 #endregion 77 78 #region User Information 79 80 public static string UserLogonName 81 { 82 get { return GetUserName(); } 83 } 84 85 public static WindowsIdentity CurrentIdentity 86 { 87 get { return GetCurrentUser(); } 88 } 89 90 public static bool IsAnonymous 91 { 92 get { return GetCurrentUser().IsAnonymous; } 93 } 94 95 #endregion 96 97 #region public methods 98 99 /// <summary> 100 /// Checks to see if a user is within a pre defined role. 101 /// You must pass a single role to this function or it will error. 102 /// To check multiple roles at once with a bitwise operation use <see cref="IsInAnyRole"/> 103 /// or <see cref="IsInAllRoles"/>. 104 /// </summary> 105 /// <param name="role"></param> 106 /// <returns>True if user is in the role</returns> 107 /// <exception cref="ConfigurationErrorsException"/> 108 public static bool IsInRole(ApplicationRole role) 109 { 110 string[] roles = GetRoleName(role).Split(';'); 111 foreach (string roleName in roles) 112 { 113 if (Thread.CurrentPrincipal.IsInRole(roleName)) 114 return true; 115 } 116 return false; 117 } 118 119 /// <summary> 120 /// Confirms user is in at least 1 of the roles. 121 /// Usage: IsInAnyRole(Role_User | Role_Editor) 122 /// </summary> 123 /// <param name="roles"></param> 124 /// <returns></returns> 125 public static bool IsInAnyRole(ApplicationRole roles) 126 { 127 foreach (string roleName in Enum.GetNames(typeof (ApplicationRole))) 128 { 129 ApplicationRole currentRole = (ApplicationRole) Enum.Parse(typeof (ApplicationRole), roleName); 130 if ((currentRole & roles) == currentRole) 131 { 132 bool success = IsInRole(currentRole); 133 if (success) 134 { 135 return true; 136 } 137 } 138 } 139 return false; 140 } 141 142 /// <summary> 143 /// Confirms user is in ALL of the specified roles. 144 /// Usage: IsInAllRoles(Role_Administrator | Role_Editor) 145 /// </summary> 146 /// <param name="roles"></param> 147 /// <returns></returns> 148 public static bool IsInAllRoles(ApplicationRole roles) 149 { 150 foreach (string roleName in Enum.GetNames(typeof (ApplicationRole))) 151 { 152 ApplicationRole currentRole = (ApplicationRole) Enum.Parse(typeof (ApplicationRole), roleName); 153 if ((currentRole & roles) == currentRole) 154 { 155 if (!IsInRole(currentRole)) 156 return false; 157 } 158 } 159 return true; 160 } 161 162 #endregion 163 164 #region Private helper functions 165 166 private static WindowsIdentity GetCurrentUser() 167 { 168 WindowsIdentity identity = WindowsIdentity.GetCurrent(); 169 return identity; 170 } 171 172 private static string GetRoleName(ApplicationRole role) 173 { 174 return GetSetting(Enum.GetName(typeof (ApplicationRole), role)); 175 } 176 177 private static string GetUserName() 178 { 179 return GetCurrentUser().Name; 180 } 181 182 private static string GetSetting(string key) 183 { 184 NameValueCollection settings = 185 WebConfigurationManager.GetWebApplicationSection(_ConfigSectionName) as NameValueCollection; 186 //Ensure the section exists 187 if (settings == null) 188 { 189 throw new ConfigurationErrorsException("The application section (" + _ConfigSectionName + 190 ") does not exist in the configuration file."); 191 } 192 string settingValue = settings[key]; 193 //If the value is null then it doesn't exist 194 if (settingValue == null) 195 { 196 throw new ConfigurationErrorsException("The application setting (" + key + 197 ") does not exist in the configuration file."); 198 } 199 return settingValue; 200 } 201 202 #endregion 203 } 204}