1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.web.jaxrs;
20
21
22 import org.apache.shiro.authz.annotation.RequiresAuthentication;
23 import org.apache.shiro.authz.annotation.RequiresGuest;
24 import org.apache.shiro.authz.annotation.RequiresPermissions;
25 import org.apache.shiro.authz.annotation.RequiresRoles;
26 import org.apache.shiro.authz.annotation.RequiresUser;
27 import org.apache.shiro.authz.aop.AuthenticatedAnnotationHandler;
28 import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;
29 import org.apache.shiro.authz.aop.GuestAnnotationHandler;
30 import org.apache.shiro.authz.aop.PermissionAnnotationHandler;
31 import org.apache.shiro.authz.aop.RoleAnnotationHandler;
32 import org.apache.shiro.authz.aop.UserAnnotationHandler;
33
34 import javax.ws.rs.container.ContainerRequestContext;
35 import javax.ws.rs.container.ContainerRequestFilter;
36 import javax.ws.rs.ext.Provider;
37 import java.io.IOException;
38 import java.lang.annotation.Annotation;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.Map;
43
44
45
46
47
48
49
50 public class AnnotationAuthorizationFilter implements ContainerRequestFilter {
51
52 private final Map<AuthorizingAnnotationHandler, Annotation> authzChecks;
53
54 public AnnotationAuthorizationFilter(Collection<Annotation> authzSpecs) {
55 Map<AuthorizingAnnotationHandler, Annotation> authChecks = new HashMap<AuthorizingAnnotationHandler, Annotation>(authzSpecs.size());
56 for (Annotation authSpec : authzSpecs) {
57 authChecks.put(createHandler(authSpec), authSpec);
58 }
59 this.authzChecks = Collections.unmodifiableMap(authChecks);
60 }
61
62 private static AuthorizingAnnotationHandler createHandler(Annotation annotation) {
63 Class<?> t = annotation.annotationType();
64 if (RequiresPermissions.class.equals(t)) return new PermissionAnnotationHandler();
65 else if (RequiresRoles.class.equals(t)) return new RoleAnnotationHandler();
66 else if (RequiresUser.class.equals(t)) return new UserAnnotationHandler();
67 else if (RequiresGuest.class.equals(t)) return new GuestAnnotationHandler();
68 else if (RequiresAuthentication.class.equals(t)) return new AuthenticatedAnnotationHandler();
69 else throw new IllegalArgumentException("Cannot create a handler for the unknown for annotation " + t);
70 }
71
72 @Override
73 public void filter(ContainerRequestContext requestContext) throws IOException {
74
75 for (Map.Entry<AuthorizingAnnotationHandler, Annotation> authzCheck : authzChecks.entrySet()) {
76 AuthorizingAnnotationHandler handler = authzCheck.getKey();
77 Annotation authzSpec = authzCheck.getValue();
78 handler.assertAuthorized(authzSpec);
79 }
80 }
81
82 }