Support ability to scope how global behaviors are applied to clients and services...
[castle.git] / Facilities / Security / Castle.Facilities.SecurityManagement / SecurityInterceptor.cs
blob7fe570df54756783350f2d5220af3bf208d16f4f
1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle.Facilities.SecurityManagement
17 using System.Reflection;
18 using System.Security;
19 using System.Threading;
20 using Castle.MicroKernel;
21 using Castle.Core.Interceptor;
22 using Castle.Services.Security;
24 /// <summary>
25 /// Summary description for SecurityInterceptor.
26 /// </summary>
27 public class SecurityInterceptor : IMethodInterceptor
29 private IKernel _kernel;
31 public SecurityInterceptor(IKernel kernel)
33 _kernel = kernel;
36 public object Intercept(IMethodInvocation invocation, params object[] args)
38 MethodInfo methodInfo = invocation.MethodInvocationTarget;
40 if (!methodInfo.IsDefined( typeof(PermissionAttribute), true ))
42 return invocation.Proceed(args);
44 else
46 object[] attrs = methodInfo.GetCustomAttributes( typeof(PermissionAttribute), true );
48 PermissionAttribute permissionAtt = (PermissionAttribute) attrs[0];
50 ISecurityManager manager = (ISecurityManager) _kernel[ typeof(ISecurityManager) ];
52 IPolicy policy =
53 manager.Generate(
54 permissionAtt, Thread.CurrentPrincipal );
56 if (policy == null)
58 return invocation.Proceed(args);
61 object value = null;
63 if(policy.Evaluate())
65 value = invocation.Proceed(args);
67 else
69 throw new SecurityException("Not Allowed");
72 return value;