javax.annotation.security.DenyAll Java Examples

The following examples show how to use javax.annotation.security.DenyAll. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthDynamicFeature.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
    final Annotation[][] parameterAnnotations = am.getParameterAnnotations();
    if (am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) ||
        am.isAnnotationPresent(PermitAll.class)) {
        context.register(authFilter);
    } else {
        for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Auth) {
                    context.register(authFilter);
                    return;
                }
            }
        }
    }
}
 
Example #2
Source File: SecurityAnnotationParser.java    From peer-os with Apache License 2.0 6 votes vote down vote up
private Annotation getAuthAnnotation( AnnotatedElement element )
{
    Annotation ann = element.getAnnotation( DenyAll.class );

    if ( ann == null )
    {
        ann = element.getAnnotation( RolesAllowed.class );
    }
    if ( ann == null )
    {
        ann = element.getAnnotation( PermitAll.class );
    }
    if ( ann == null )
    {
        ann = element.getAnnotation( RelationCredibility.class );
    }
    return ann;
}
 
Example #3
Source File: SecurityConstraintTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    resourceMethod = mock(GenericResourceMethod.class);
    permitAll = mock(PermitAll.class);
    when(permitAll.annotationType()).thenReturn((Class)PermitAll.class);
    denyAll = mock(DenyAll.class);
    when(denyAll.annotationType()).thenReturn((Class)DenyAll.class);
    rolesAllowed = mock(RolesAllowed.class);
    when(rolesAllowed.annotationType()).thenReturn((Class)RolesAllowed.class);
    when(rolesAllowed.value()).thenReturn(new String[]{"user"});
    ApplicationContext applicationContext = mock(ApplicationContext.class);
    securityContext = mock(SecurityContext.class);
    when(applicationContext.getSecurityContext()).thenReturn(securityContext);
    ApplicationContext.setCurrent(applicationContext);

    securityConstraint = new SecurityConstraint();
}
 
Example #4
Source File: SecurityConstraint.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Check does <tt>method</tt> contains one on of security annotations PermitAll, DenyAll, RolesAllowed.
 *
 * @see PermitAll
 * @see DenyAll
 * @see RolesAllowed
 */
@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());
        }
    }
}
 
Example #5
Source File: JWTAuthorizationFilterRegistrar.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Annotation mpJwtAnnotation = getMpJwtAnnotation(resourceInfo);
    if (mpJwtAnnotation != null) {
        if (mpJwtAnnotation instanceof DenyAll) {
            configureDenyAll(context);
        } else if (mpJwtAnnotation instanceof RolesAllowed) {
            configureRolesAllowed((RolesAllowed) mpJwtAnnotation, context);
        }
    } else {
        // the resource method is not annotated and the class is not annotated either
        if (hasSecurityAnnotations(resourceInfo) && shouldNonannotatedMethodsBeDenied()) {
            // some other method has a security annotation and this one doesn't, it should be @DenyAll by default
            configureDenyAll(context);
        }
    }
}
 
Example #6
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_DisallowAnonymousAccess_When_AnonymousAllowedIsOverriddenWithDenyAll()
        throws Exception {
    @AnonymousAllowed
    class Test {
        @DenyAll
        public void test() {
        }
    }

    createAnonymousContext();
    shouldFail(Test.class);
}
 
Example #7
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_DisallowAnonymousAccess_When_DenyAllAndAnonymousAllowed()
        throws Exception {
    class Test {
        @DenyAll
        @AnonymousAllowed
        public void test() {
        }
    }
    createAnonymousContext();
    shouldFail(Test.class);
}
 
Example #8
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_DisallowAnyAuthenticatedAccess_When_DenyAllAndAnonymousAllowed()
        throws Exception {
    class Test {
        @DenyAll
        @AnonymousAllowed
        public void test() {
        }
    }
    shouldFail(Test.class);
}
 
Example #9
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test()
public void should_Pass_When_DenyAllClass_PermitAllMethod()
        throws Exception {
    @DenyAll
    class Test {
        @PermitAll
        public void test() {
        }
    }
    shouldPass(Test.class);
}
 
Example #10
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test()
public void should_Pass_When_DenyAllClass_ValidRoleMethod()
        throws Exception {
    @DenyAll
    class Test {
        @RolesAllowed(ROLE_USER)
        public void test() {
        }
    }
    shouldPass(Test.class);
}
 
Example #11
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_Fail_When_DenyAllClass() throws Exception {
    @DenyAll
    class Test {
        public void test() {
        }
    }
    shouldFail(Test.class);
}
 
Example #12
Source File: AbstractEndpointGenerationTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void assertPaths(Paths actualPaths,
        List<Class<?>> testEndpointClasses) {
    int pathCount = 0;
    for (Class<?> testEndpointClass : testEndpointClasses) {
        for (Method expectedEndpointMethod : testEndpointClass
                .getDeclaredMethods()) {
            if (!Modifier.isPublic(expectedEndpointMethod.getModifiers())
                    || accessChecker
                            .getSecurityTarget(expectedEndpointMethod)
                            .isAnnotationPresent(DenyAll.class)) {
                continue;
            }
            pathCount++;
            String expectedEndpointUrl = String.format("/%s/%s",
                    getEndpointName(testEndpointClass),
                    expectedEndpointMethod.getName());
            PathItem actualPath = actualPaths.get(expectedEndpointUrl);
            assertNotNull(String.format(
                    "Expected to find a path '%s' for the endpoint method '%s' in the class '%s'",
                    expectedEndpointUrl, expectedEndpointMethod,
                    testEndpointClass), actualPath);
            assertPath(testEndpointClass, expectedEndpointMethod, actualPath);
        }
    }
    assertEquals("Unexpected number of OpenAPI paths found", pathCount,
            actualPaths.size());
}
 
Example #13
Source File: SecurityInterceptor.java    From hammock with Apache License 2.0 5 votes vote down vote up
private void checkLoggedIn(InvocationContext invocationContext) {
    LoggedIn loggedIn = AnnotationUtil.getAnnotation(invocationContext, LoggedIn.class);
    DenyAll denyAll = AnnotationUtil.getAnnotation(invocationContext, DenyAll.class);
    if (loggedIn != null || denyAll != null) {
        if(!identity.isLoggedIn()) {
            throw new NotLoggedInException(identity+" Not logged in");
        }
    }
}
 
Example #14
Source File: VaadinConnectAccessChecker.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean entityForbidden(AnnotatedElement entity,
        HttpServletRequest request) {
    return entity.isAnnotationPresent(DenyAll.class) || (!entity
            .isAnnotationPresent(AnonymousAllowed.class)
            && !roleAllowed(entity.getAnnotation(RolesAllowed.class),
                    request));
}
 
Example #15
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean isAccessForbidden(
        ClassOrInterfaceDeclaration typeDeclaration,
        MethodDeclaration methodDeclaration) {
    return !methodDeclaration.isPublic()
            || (hasSecurityAnnotation(methodDeclaration)
                    ? methodDeclaration.isAnnotationPresent(DenyAll.class)
                    : typeDeclaration.isAnnotationPresent(DenyAll.class));
}
 
Example #16
Source File: RolesAllowedChecker.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Scope scope) {

    AnnotatedMethod am = new AnnotatedMethod(scope.getInvokedMethod());

    // DenyAll on the method take precedence over RolesAllowed and PermitAll
    if (am.isAnnotationPresent(DenyAll.class)) {
        return false;
    }

    // RolesAllowed on the method takes precedence over PermitAll
    RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
    if (ra != null) {
        return checkRoles(ra.value());
    }

    // PermitAll takes precedence over RolesAllowed on the class
    if (am.isAnnotationPresent(PermitAll.class)) {
        // Do nothing.
        return true;
    }

    // DenyAll can't be attached to classes

    // RolesAllowed on the class takes precedence over PermitAll
    ra = scope.getInvokedClass().getAnnotation(RolesAllowed.class);
    if (ra != null) {
        return checkRoles(ra.value());
    }
    return true;
}
 
Example #17
Source File: RolesAllowedDynamicFeatureImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext configuration) {
    final Method am = resourceInfo.getResourceMethod();
    try {
        // DenyAll on the method take precedence over RolesAllowed and PermitAll
        if (am.isAnnotationPresent(DenyAll.class)) {
            configuration.register(new RolesAllowedRequestFilter());
            return;
        }

        // RolesAllowed on the method takes precedence over PermitAll
        Optional<Annotation> ra = Arrays.stream(am.getAnnotations())
                .filter(a -> a.annotationType().getName().equals(RolesAllowed.class.getName())).findFirst();
        if (ra.isPresent()) {
            configuration.register(new RolesAllowedRequestFilter(((RolesAllowed) ra.get()).value()));
            return;
        }

        // PermitAll takes precedence over RolesAllowed on the class
        if (am.isAnnotationPresent(PermitAll.class)) {
            // Do nothing.
            return;
        }

        // DenyAll can't be attached to classes

        // RolesAllowed on the class takes precedence over PermitAll
        ra = Arrays.stream(resourceInfo.getResourceClass().getAnnotations())
                .filter(a -> a.annotationType().getName().equals(RolesAllowed.class.getName())).findFirst();
        if (ra.isPresent()) {
            configuration.register(new RolesAllowedRequestFilter(((RolesAllowed) ra.get()).value()));
        }
    } catch (Exception e) {
        logger.error("Error while configuring the roles", e);
    }
}
 
Example #18
Source File: RolesAnnotationFilter.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
  final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());

  // DenyAll on the method take precedence over RolesAllowed and PermitAll
  if (am.isAnnotationPresent(DenyAll.class)) {
    context.register(new RolesAllowedRequestFilter());
    return;
  }

  // RolesAllowed on the method takes precedence over PermitAll
  RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
  if (ra != null) {
    context.register(new RolesAllowedRequestFilter(ra.value()));
    return;
  }

  // PermitAll takes precedence over RolesAllowed on the class
  if (am.isAnnotationPresent(PermitAll.class)) {
    // Do nothing.
    return;
  }

  // DenyAll can't be attached to classes

  // RolesAllowed on the class takes precedence over PermitAll
  ra = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
  if (ra != null) {
    context.register(new RolesAllowedRequestFilter(ra.value()));
  }
}
 
Example #19
Source File: TokenSecuredResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@GET()
@Path("deny-all")
@DenyAll
@Produces(MediaType.TEXT_PLAIN)
public String helloShouldDeny(@Context SecurityContext ctx) {
    Principal caller = ctx.getUserPrincipal();
    String name = caller == null ? "anonymous" : caller.getName();
    return "hello + " + name;
}
 
Example #20
Source File: TestAuthorizationRest.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/nobody")
@Produces(MediaType.TEXT_PLAIN)
@DenyAll()
public String nobody() {

	return "nobody";
}
 
Example #21
Source File: RolesAllowedScopeScanTests.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
@GET
@Path("locked")
@Produces("application/json")
@DenyAll
public Response getLockedData(int id) {
    return null;
}
 
Example #22
Source File: SubjectExposingResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    String name = user != null ? user.getName() : "anonymous";
    return name;
}
 
Example #23
Source File: SubjectExposingResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    String name = user != null ? user.getName() : "anonymous";
    return name;
}
 
Example #24
Source File: SubjectExposingResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    String name = user != null ? user.getName() : "anonymous";
    return name;
}
 
Example #25
Source File: PermissionCheckTest.java    From jump-the-queue with Apache License 2.0 5 votes vote down vote up
/**
 * Check if all relevant methods in use case implementations have permission checks i.e. {@link RolesAllowed},
 * {@link DenyAll} or {@link PermitAll} annotation is applied. This is only checked for methods that are declared in
 * the corresponding interface and thus have the {@link Override} annotations applied.
 */
@Test
@Ignore // Currently Access control has not been implemented in jumpthequeue so the test is ignored
public void permissionCheckAnnotationPresent() {

  String packageName = "com.devonfw.application.jtqj";
  Filter<String> filter = new Filter<String>() {

    @Override
    public boolean accept(String value) {

      return value.contains(".logic.impl.usecase.Uc") && value.endsWith("Impl");
    }

  };
  ReflectionUtil ru = ReflectionUtilImpl.getInstance();
  Set<String> classNames = ru.findClassNames(packageName, true, filter);
  Set<Class<?>> classes = ru.loadClasses(classNames);
  SoftAssertions assertions = new SoftAssertions();
  for (Class<?> clazz : classes) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
      Method parentMethod = ru.getParentMethod(method);
      if (parentMethod != null) {
        Class<?> declaringClass = parentMethod.getDeclaringClass();
        if (declaringClass.isInterface() && declaringClass.getSimpleName().startsWith("Uc")) {
          boolean hasAnnotation = false;
          if (method.getAnnotation(RolesAllowed.class) != null || method.getAnnotation(DenyAll.class) != null
              || method.getAnnotation(PermitAll.class) != null) {
            hasAnnotation = true;
          }
          assertions.assertThat(hasAnnotation)
              .as("Method " + method.getName() + " in Class " + clazz.getSimpleName() + " is missing access control")
              .isTrue();
        }
      }
    }
  }
  assertions.assertAll();
}
 
Example #26
Source File: SubjectExposingResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    String name = user != null ? user.getName() : "anonymous";
    return name;
}
 
Example #27
Source File: SecurityInterceptor.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
	ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
			.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
	Method method = methodInvoker.getMethod();
	// Access allowed for all
	if (!method.isAnnotationPresent(PermitAll.class)) {
		// Access denied for all
		if (method.isAnnotationPresent(DenyAll.class)) {
			requestContext.abortWith(ACCESS_FORBIDDEN);
			return;
		}

		// Get request headers
		final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();

		// Fetch authorization header
		final List<String> authorization = headersMap.get(AUTHORIZATION_PROPERTY);

		// If no authorization information present; block access
		if (authorization == null || authorization.isEmpty()) {
			requestContext.abortWith(ACCESS_DENIED);
			return;
		}

		// Get encoded username and password
		final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

		// Decode username and password
		String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword));

		// Split username and password tokens
		final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
		final String username = tokenizer.nextToken();
		final String password = tokenizer.nextToken();

		// Verify user access
		if (method.isAnnotationPresent(RolesAllowed.class)) {
			RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
			Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));

			// Is user valid?
			if (!isUserAllowed(username, password, rolesSet)) {
				requestContext.abortWith(ACCESS_DENIED);
				return;
			}
		}
	}
}
 
Example #28
Source File: AnnotatedSLSB.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@DenyAll
public void restrictedMethod() {
    throw new RuntimeException("This method was supposed to be restricted to all!");
}
 
Example #29
Source File: StatefulSecurityPermissionsTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@DenyAll
public String color(final Object o) {
    return attribute();
}
 
Example #30
Source File: SecurityTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
@DenyAll
public String deleteProject(final String s) {
    return s;
}