You are here: Code Zone » Security Library
 Register    Login 
Code Zone Minimize  

Free Source Code Minimize 

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.


Related Links Minimize  

Security Code Library Minimize  
RijndaelEncryption.cs
AzManPermission.cs
Impersonator.cs
ApplicationSecurity.cs
IdentityManager.cs
InputValidators.cs
1using System;
2using System.Collections;
3using System.Configuration;
4using System.Security;
5using System.Security.Principal;
6
7namespace Enterprise.Security
8{
9    /// <!-- 
10    ///     Code Courtesy Of http://www.purecoding.net
11    ///     Permissions : Free for general use
12    ///     Keywords: Security, AzMan, Authorization Manager, Identity, c#, .Net, Windows, Aspnet. 
13    ///     Filename: AzManPermission.cs
14    /// -->
15
16    #region AzManPermission Enum - reflects the AzMan Operations
17
18    //The enum is used to reflect the real operation name in 
19    //AzMan. These enum names must exist in the AzMan store as AzMan 
20    //Operations.
21    public enum AzManOperationEnum
22    {
23        CustomerCreate, // Insert Customer
24        CustomerUpdate, //Save any Customer
25        CustomerSearch, //Search Customers
26        CustomerLoad, //Load the details of an Customer
27    }
28
29    #endregion
30
31    /// <summary>
32    /// Permission for the system. Integrates with AzMan.
33    /// You can add multiple permissions with the .AddPermission method.
34    /// Simple Usage: AzManPermission.Demand(AzManOperationEnum.CustomerUpdate, "Id: 1234");
35    /// Note: You can add multiple permissions:
36    /// AzManPermission permission = new AzManPermission();
37    /// permission.AddPermission(AzManOperationEnum.CustomerLoad, "Id: 1234");
38    /// permission.AddPermission(AzManOperationEnum.CustomerSearch, "Id: 1234");
39    /// permission.Demand();  //throws a SecurityException if no permission.
40    /// </summary>
41    /// <remarks>This interface is the same approach as CAS
42    /// call, .Demand() to throw a security exception.
43    /// Only authorises Operations via the Enterprise Security Block (May 07 3.1)
44    /// Note: This class uses IdentityManager and Log which are available from 
45    /// www.purecoding.net, or you can replace with your own code.
46    /// Use the Configuration Application from the Enterprise Library to
47    /// configure your app or web.config.  To create AzMan operations you need to 
48    /// logon to the Domain Controller (or install the Windows 2003 Admin Pack),
49    /// run MMC, add the Authorization Manager snap in.  Make sure you switch to
50    /// Developer mode or you will not see the Operations tab.
51    /// When you set your configuration, ensure you set the provider name to 
52    /// "Default Provider", or update the method GetRuleProvider() in this class.
53    /// </remarks>
54    public class AzManPermission
55    {
56        #region Class Vars and Ctors
57
58        private readonly IIdentity _CallerIdentity;
59        private readonly Hashtable _Permissions = new Hashtable();
60
61        public AzManPermission()
62        {
63            _CallerIdentity = IdentityManager.CurrentUser();
64        }
65
66        public AzManPermission(IIdentity identityOfCaller)
67        {
68            _CallerIdentity = identityOfCaller;
69        }
70
71        #endregion
72
73        #region Permission Collection Management
74
75        public void Clear()
76        {
77            _Permissions.Clear();
78        }
79
80        public void AddPermission(AzManOperationEnum permission, string target)
81        {
82            string requestedPermission = GetPermissionData(permission);
83            if (!_Permissions.Contains(requestedPermission))
84            {
85                _Permissions.Add(requestedPermission, target);
86            }
87        }
88
89        public void RemovePermission(AzManOperationEnum permission)
90        {
91            string requestedPermission = GetPermissionData(permission);
92            if (_Permissions.Contains(requestedPermission))
93            {
94                _Permissions.Remove(requestedPermission);
95            }
96        }
97
98        #endregion
99
100        #region Authorisation and AzMan Integration
101
102        public static void Demand(AzManOperationEnum permission, string target,
103                                  IIdentity callerToAuthorise)
104        {
105            AzManPermission appPermission =
106                new AzManPermission(callerToAuthorise);
107            appPermission.AddPermission(permission, target);
108            appPermission.Demand();
109        }
110
111        public static void Demand(AzManOperationEnum permission, string target)
112        {
113            AzManPermission appPermission = new AzManPermission();
114            appPermission.AddPermission(permission, target);
115            appPermission.Demand();
116        }
117
118        public void Demand()
119        {
120            foreach (string key in _Permissions.Keys)
121            {
122                Authorise(key, (string) _Permissions[key]);
123            }
124        }
125
126        public void DemandAuthenticated()
127        {
128            DemandAuthenticated(_CallerIdentity);
129        }
130
131        public void DemandAuthenticated(IIdentity callerToAuthorise)
132        {
133            if (!callerToAuthorise.IsAuthenticated)
134            {
135                throw new SecurityException(
136                    "You are not authenticated.  Anonymous access denied.");
137            }
138        }
139
140        public static bool Peek(AzManOperationEnum permission, IIdentity caller)
141        {
142            if (caller == null)
143            {
144                throw new ArgumentNullException("caller");
145            }
146            IPrincipal principal = GetPrincipal(caller);
147            IAuthorizationProvider ruleProvider = GetRuleProvider();
148            string resourceOrFunction = GetPermissionData(permission);
149            string operation = GetAsOperation(resourceOrFunction);
150            try
151            {
152                return ruleProvider.Authorize(principal, operation);
153            }
154            catch (Exception ex)
155            {
156                throw new ConfigurationErrorsException(
157                    "Unable to appropriately authorise security with AzMan. " +
158                    " Most likely this is a configuration or permission problem. Operation " +
159                    resourceOrFunction,
160                    ex);
161            }
162        }
163
164        private void Authorise(string resourceOrFunction, string target)
165        {
166            try
167            {
168                if (string.IsNullOrEmpty(resourceOrFunction))
169                {
170                    throw new ArgumentNullException("resourceOrFunction");
171                }
172                DemandAuthenticated();
173                bool authorised;
174                IPrincipal principal = GetPrincipal(_CallerIdentity);
175                IAuthorizationProvider ruleProvider = GetRuleProvider();
176                string operation = GetAsOperation(resourceOrFunction);
177
178                try
179                {
180                    authorised = ruleProvider.Authorize(principal, operation);
181                }
182                catch (Exception ex)
183                {
184                    throw new ConfigurationErrorsException(
185                        "Unable to appropriately authorise security with AzMan. " + 
186                        " Most likely this is a configuration or permission problem.",
187                        ex);
188                }
189
190                if (!authorised)
191                {
192                    Log.LogSecurityFailure(
193                        string.Format("{0} {1}", resourceOrFunction, target),
194                        _CallerIdentity);
195                    throw new SecurityException(
196                        string.Format("You do not have {0} permission.",
197                                      resourceOrFunction));
198                }
199                Log.LogSecuritySuccess(
200                    string.Format("{0} {1}", resourceOrFunction, target),
201                    _CallerIdentity);
202            }
203            catch (SecurityException ex)
204            {
205                if (ex.Message.Contains("Element not found"))
206                {
207                    string errorMsg =
208                        string.Format(
209                            "When requesting authorisation for operation ({0}) an " + 
210                            "exception with Element Not Found was received.  Please open" + 
211                            " the AzMan Console, and ensure the operation exists.",
212                            resourceOrFunction);
213                    Log.LogError(LogCategory.SL, "Invalid AzMan Configuration",
214                                 errorMsg, ex);
215                    throw new ConfigurationErrorsException(errorMsg, ex);
216                        //These happen if AzMan config is bad.
217                }
218                throw; //These are planned for.
219            }
220            catch (Exception ex)
221            {
222                //These are NOT planned for and probably means someone 
223                //has screwed up the AzMan config. 
224                //One reason for this is that the current security context
225                //doesn't have permission to call azman.  Check the AzMan permissions from
226                //the snapin.
227                string error =
228                    string.Format(
229                        "Unplanned Exception Authorising User {0} for Permission {1} to Resource ({2})",
230                        SecurityManager.CurrentUser().Name, resourceOrFunction,
231                        target);
232                Log.LogError(LogCategory.All, "Invalid Security Configuration",
233                             "Failed to call authorisation provider. " + error,
234                             ex);
235                Log.LogSecurityFailure(
236                    string.Format(
237                        "Possible Invalid Configuration, error trying to authorise {0} {1}",
238                        resourceOrFunction, target), _CallerIdentity);
239                throw;
240            }
241        }
242
243        private static IAuthorizationProvider GetRuleProvider()
244        {
245            //Note: This provider name is specified in your app or web.config.
246            return
247                AuthorizationFactory.GetAuthorizationProvider("Default Provider");
248        }
249
250        private static IPrincipal GetPrincipal(IIdentity caller)
251        {
252            return new GenericPrincipal(caller, null);
253        }
254
255        private static string GetAsOperation(string resourceOrFunction)
256        {
257            string operation = resourceOrFunction;
258            if (resourceOrFunction.StartsWith("o:"))
259            {
260                operation = resourceOrFunction.Replace("o:", "O:");
261            }
262            else if (!resourceOrFunction.StartsWith("O:"))
263            {
264                operation = "O:" + resourceOrFunction;
265            }
266            return operation;
267        }
268
269        #endregion
270
271        #region Helpers
272
273        private static string GetPermissionData(AzManOperationEnum permission)
274        {
275            return Enum.GetName(typeof (AzManOperationEnum), permission);
276        }
277
278        #endregion
279    }
280}

 Copyright 2008 PureCoding.net
 Terms Of Use     Privacy Statement