View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.security;
21  
22  import org.slf4j.Logger;
23  import org.slf4j.LoggerFactory;
24  
25  import javax.annotation.security.DenyAll;
26  import javax.annotation.security.PermitAll;
27  import javax.annotation.security.RolesAllowed;
28  import javax.faces.context.FacesContext;
29  import java.lang.annotation.Annotation;
30  import java.lang.reflect.AnnotatedElement;
31  import java.lang.reflect.Method;
32  import java.util.ArrayList;
33  import java.util.Arrays;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.concurrent.ConcurrentHashMap;
37  import java.util.regex.Matcher;
38  import java.util.regex.Pattern;
39  
40  public class AuthorizationUtils {
41    private static final Logger LOG = LoggerFactory.getLogger(AuthorizationUtils.class);
42  
43    private static final Object NULL_VALUE = new Object();
44    private static final Map<String, Object> AUTHORISATION_CACHE = new ConcurrentHashMap<String, Object>();
45  
46    private static final Pattern PATTERN = Pattern.compile("#\\{(\\w+(?:\\.\\w+)*)\\.(\\w+)(?:\\(.*\\))?\\}");
47  
48    private AuthorizationUtils() {
49    }
50  
51    public static boolean isAuthorized(final FacesContext facesContext, final String expression) {
52  
53      final Annotation securityAnnotation = getSecurityAnnotation(facesContext, expression);
54      if (securityAnnotation == null) {
55        return true;
56      }
57  
58      if (securityAnnotation instanceof DenyAll) {
59        if (LOG.isDebugEnabled()) {
60          LOG.debug("DenyAll");
61        }
62        return false;
63      }
64      if (securityAnnotation instanceof RolesAllowed) {
65        final String [] roles = ((RolesAllowed) securityAnnotation).value();
66        if (LOG.isDebugEnabled()) {
67          LOG.debug("RolesAllowed " + Arrays.asList(((RolesAllowed) securityAnnotation).value()));
68        }
69        for (final String role : roles) {
70          final boolean authorised = facesContext.getExternalContext().isUserInRole(role);
71          if (authorised) {
72            return true;
73          }
74        }
75        return false;
76      }
77      if (securityAnnotation instanceof PermitAll) {
78        if (LOG.isDebugEnabled()) {
79          LOG.debug("PermitAll");
80        }
81        return true;
82      }
83      return true;
84    }
85  
86    private static Annotation getSecurityAnnotations(final AnnotatedElement annotatedElement) {
87      Annotation annotation = annotatedElement.getAnnotation(RolesAllowed.class);
88      if (annotation != null) {
89        return annotation;
90      }
91      annotation = annotatedElement.getAnnotation(DenyAll.class);
92      if (annotation != null) {
93        return annotation;
94      }
95      annotation = annotatedElement.getAnnotation(PermitAll.class);
96      if (annotation != null) {
97        return annotation;
98      }
99      return null;
100   }
101 
102   private static Annotation getSecurityAnnotation(final FacesContext facesContext, String expression) {
103     if (AUTHORISATION_CACHE.containsKey(expression)) {
104       final Object obj = AUTHORISATION_CACHE.get(expression);
105       if (obj instanceof Annotation) {
106         return (Annotation) obj;
107       }
108       return null;
109     } else {
110       Annotation securityAnnotation = null;
111       final Matcher matcher = PATTERN.matcher(expression);
112       if (matcher.matches()) {
113         String beanString = matcher.group(1);
114         String methodString = matcher.group(2);
115         final Object bean =
116             facesContext.getELContext().getELResolver().getValue(facesContext.getELContext(), null, beanString);
117         if (bean != null) {
118           final List<Method> methods = findMethods(bean, methodString);
119           switch (methods.size()) {
120             case 0:
121               LOG.error("No Method '" + methodString + "' in class " + bean.getClass());
122               break;
123             case 1:
124               securityAnnotation = getSecurityAnnotations(methods.get(0));
125               if (securityAnnotation == null) {
126                 securityAnnotation = getSecurityAnnotations(bean.getClass());
127               }
128               break;
129             default:
130               LOG.warn("Method name ambiguous '" + methodString + "' in class " + bean.getClass()
131                   + ". Found " + methods.size() + " but only 1 is supported, yet.");
132           }
133         }
134       }
135       if (securityAnnotation != null) {
136         AUTHORISATION_CACHE.put(expression, securityAnnotation);
137       } else {
138         AUTHORISATION_CACHE.put(expression, NULL_VALUE);
139       }
140       return securityAnnotation;
141     }
142   }
143 
144   private static List<Method> findMethods(Object bean, String name) {
145     final Method[] methods = bean.getClass().getMethods();
146     final List<Method> result = new ArrayList<Method>();
147     for (Method method : methods) {
148       if (method.getName().equals(name)) {
149         result.add(method);
150       }
151     }
152     return result;
153   }
154 }