SecurityConstraint implements MethodInvokerFilter { @Override public void accept(GenericResourceMethod method, Object[] params) throws WebApplicationException { for (Annotation annotation : method.getAnnotations()) { Class<?> annotationType = annotation.annotationType(); if (annotationType == PermitAll.class) { return; } else if (annotationType == DenyAll.class) { throw new WebApplicationException(Response.status(FORBIDDEN) .entity("User not authorized to call this method").type(TEXT_PLAIN) .build()); } else if (annotationType == RolesAllowed.class) { SecurityContext security = ApplicationContext.getCurrent().getSecurityContext(); for (String role : ((RolesAllowed)annotation).value()) { if (security.isUserInRole(role)) { return; } } throw new WebApplicationException(Response.status(FORBIDDEN) .entity("User not authorized to call this method").type(TEXT_PLAIN) .build()); } } }  @Override void accept(GenericResourceMethod method, Object[] params);  }
@Test public void allowsAccessWhenPermitAllAnnotationPresents() { when(resourceMethod.getAnnotations()).thenReturn(new Annotation[] {permitAll}); securityConstraint.accept(resourceMethod, null); }
@Test public void allowsAccessWhenSecurityAnnotationAbsents() { when(resourceMethod.getAnnotations()).thenReturn(new Annotation[0]); securityConstraint.accept(resourceMethod, null); }
@Test public void denysAccessWhenDenyAllAnnotationPresents() { when(resourceMethod.getAnnotations()).thenReturn(new Annotation[] {denyAll}); thrown.expect(webApplicationExceptionForbiddenMatcher()); securityConstraint.accept(resourceMethod, null); }
@Test public void allowsAccessWhenUserHasAcceptableRole() { when(resourceMethod.getAnnotations()).thenReturn(new Annotation[] {rolesAllowed}); when(securityContext.isUserInRole("user")).thenReturn(true); securityConstraint.accept(resourceMethod, null); }
@Test public void denysAccessWhenUserDoesNotHaveAcceptableRole() { when(resourceMethod.getAnnotations()).thenReturn(new Annotation[] {rolesAllowed}); when(securityContext.isUserInRole("user")).thenReturn(false); thrown.expect(webApplicationExceptionForbiddenMatcher()); securityConstraint.accept(resourceMethod, null); }