io.vertx.ext.auth.authorization.AuthorizationContext Java Examples

The following examples show how to use io.vertx.ext.auth.authorization.AuthorizationContext. 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: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch2(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertFalse(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r2", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #2
Source File: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertTrue(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #3
Source File: PermissionBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch2(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", PermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertEquals(false, PermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r2", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #4
Source File: PermissionBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", PermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertEquals(true, PermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #5
Source File: WildcardPermissionBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch2(TestContext should) {
  final Async test = should.async();
  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", WildcardPermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertFalse(WildcardPermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r2", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #6
Source File: WildcardPermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  User user = context.user();
  if (user != null) {
    Authorization resolvedAuthorization = getResolvedAuthorization(context);
    for (String providerId: user.authorizations().getProviderIds()) {
      for (Authorization authorization : user.authorizations().get(providerId)) {
        if (authorization.verify(resolvedAuthorization)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #7
Source File: WildcardPermissionBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();
  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", WildcardPermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertTrue(WildcardPermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }
    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #8
Source File: RoleBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  User user = context.user();
  if (user != null) {
    Authorization resolvedAuthorization = getResolvedAuthorization(context);
    for (String providerId: user.authorizations().getProviderIds()) {
      for (Authorization authorization : user.authorizations().get(providerId)) {
        if (authorization.verify(resolvedAuthorization)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #9
Source File: PermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  User user = context.user();
  if (user != null) {
    Authorization resolvedAuthorization = getResolvedAuthorization(context);
    for (String providerId: user.authorizations().getProviderIds()) {
      for (Authorization authorization : user.authorizations().get(providerId)) {
        if (authorization.verify(resolvedAuthorization)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #10
Source File: AuthorizationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
  if (routingContext.user() == null) {
    routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);
  } else {
    // create the authorization context
    AuthorizationContext authorizationContext = getAuhorizationContext(routingContext);
    // check or fetch authorizations
    checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator());
  }
}
 
Example #11
Source File: UserImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public User isAuthorized(Authorization authorization, Handler<AsyncResult<Boolean>> resultHandler) {
  Objects.requireNonNull(authorization);
  Objects.requireNonNull(resultHandler);

  AuthorizationContext context = new AuthorizationContextImpl(this);
  resultHandler.handle(Future.succeededFuture(authorization.match(context)));
  return this;
}
 
Example #12
Source File: AndAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  for (Authorization authorization : authorizations) {
    if (!authorization.match(context)) {
      return false;
    }
  }
  return true;
}
 
Example #13
Source File: VariableAwareExpression.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public String resolve(AuthorizationContext context) {
  if (parts.length == 1) {
    return parts[0].apply(context);
  } else if (parts.length > 1) {
    StringBuilder result = new StringBuilder();
    for (Function<AuthorizationContext, String> part : parts) {
      result.append(part.apply(context));
    }
    return result.toString();
  }
  // should only happen when the length is 0
  return "";
}
 
Example #14
Source File: OrAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  for (Authorization authorization : authorizations) {
    if (authorization.match(context)) {
      return true;
    }
  }
  return false;
}
 
Example #15
Source File: AuthorizationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private final AuthorizationContext getAuhorizationContext(RoutingContext event) {
  final AuthorizationContext result = AuthorizationContext.create(event.user());
  if (variableHandler != null) {
    variableHandler.accept(event, result);
  }
  return result;
}
 
Example #16
Source File: AuthorizationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * this method checks that the specified authorization match the current content.
 * It doesn't fetch all providers at once in order to do early-out, but rather tries to be smart and fetch authorizations one provider at a time
 *
 * @param routingContext
 * @param authorizationContext
 * @param providers
 */
private void checkOrFetchAuthorizations(RoutingContext routingContext, AuthorizationContext authorizationContext, Iterator<AuthorizationProvider> providers) {
  if (authorization.match(authorizationContext)) {
    routingContext.next();
    return;
  }
  if (!providers.hasNext()) {
    routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);
    return;
  }

  // there was no match, in this case we do the following:
  // 1) contact the next provider we haven't contacted yet
  // 2) if there is a match, get out right away otherwise repeat 1)
  while (providers.hasNext()) {
    AuthorizationProvider provider = providers.next();
    // we haven't fetch authorization from this provider yet
    if (! routingContext.user().authorizations().getProviderIds().contains(provider.getId())) {
      provider.getAuthorizations(routingContext.user(), authorizationResult -> {
        if (authorizationResult.failed()) {
          LOG.warn("An error occured getting authorization - providerId: " + provider.getId(), authorizationResult.cause());
          // note that we don't 'record' the fact that we tried to fetch the authorization provider. therefore it will be re-fetched later-on
        }
        checkOrFetchAuthorizations(routingContext, authorizationContext, providers);
      });
      // get out right now as the callback will decide what to do next
      return;
    }
  }
}
 
Example #17
Source File: PermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
private PermissionBasedAuthorization getResolvedAuthorization(AuthorizationContext context) {
  if (resource == null || !resource.hasVariable()) {
    return this;
  }
  return PermissionBasedAuthorization.create(this.permission).setResource(resource.resolve(context));
}
 
Example #18
Source File: VariableAwareExpression.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public Function<AuthorizationContext, String>[] parts() {
  return parts;
}
 
Example #19
Source File: RoleBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
private RoleBasedAuthorization getResolvedAuthorization(AuthorizationContext context) {
  if (resource == null || !resource.hasVariable()) {
    return this;
  }
  return RoleBasedAuthorization.create(this.role).setResource(resource.resolve(context));
}
 
Example #20
Source File: NotAuthorizationImpl.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
@Override
public boolean match(AuthorizationContext context) {
  Objects.requireNonNull(context);

  return !this.authorization.match(context);
}
 
Example #21
Source File: WildcardPermissionBasedAuthorizationImpl.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
private WildcardPermissionBasedAuthorization getResolvedAuthorization(AuthorizationContext context) {
  if (resource == null || !resource.hasVariable()) {
    return this;
  }
  return WildcardPermissionBasedAuthorization.create(this.permission).setResource(resource.resolve(context));
}
 
Example #22
Source File: ServiceAuthInterceptor.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Future<Message<JsonObject>> apply(Message<JsonObject> msg) {

  final TokenCredentials authorization = new TokenCredentials(msg.headers().get("auth-token"));

  try {
    authorization.checkValid(null);

    Promise<Message<JsonObject>> promise = Promise.promise();

    if (authn == null) {
      promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, "No AuthenticationProvider present"));
      return promise.future();
    }

    authn.authenticate(authorization, authenticate -> {
      if (authenticate.failed()) {
        promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, authenticate.cause().getMessage()));
        return;
      }

      final User user = authenticate.result();

      if (user == null) {
        promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 401, "Unauthorized"));
        return;
      }

      if (authorizations == null || authorizations.isEmpty()) {
        promise.complete(msg);
        return;
      }

      authz.getAuthorizations(user, getAuthorizations -> {
        if (getAuthorizations.failed()) {
          promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, authenticate.cause().getMessage()));
        } else {
          AuthorizationContext context = AuthorizationContext.create(user);
          for (Authorization authority : authorizations) {
            if (!authority.match(context)) {
              // failed
              promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 403, "Forbidden"));
              return;
            }
          }
          // all authorities have passed
          promise.complete(msg);
        }
      });
    });

    return promise.future();
  } catch (CredentialValidationException e) {
    return Future.failedFuture(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 401, "Unauthorized"));
  }
}
 
Example #23
Source File: TestUtils.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public static AuthorizationContext getTestAuthorizationContext() {
  return getTestAuthorizationContext(User.create(new JsonObject().put("username", "dummy user")));
}
 
Example #24
Source File: TestUtils.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public static AuthorizationContext getTestAuthorizationContext(User user) {
  return null;
}
 
Example #25
Source File: AuthorizationHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationHandler variableConsumer(BiConsumer<RoutingContext, AuthorizationContext> handler) {
  this.variableHandler = handler;
  return this;
}
 
Example #26
Source File: AuthorizationHandler.java    From vertx-web with Apache License 2.0 2 votes vote down vote up
/**
 * Provide a simple handler to extract needed variables.
 * As it may be useful to allow/deny access based on the value of a request param one can do:
 * {@code (routingCtx, authCtx) -> authCtx.variables().addAll(routingCtx.request().params()) }
 *
 * Or for example the remote address:
 * {@code (routingCtx, authCtx) -> authCtx.result.variables().add(VARIABLE_REMOTE_IP, routingCtx.request().connection().remoteAddress()) }
 *
 * @param handler a bi consumer.
 * @return fluent self.
 */
@Fluent
@GenIgnore
AuthorizationHandler variableConsumer(BiConsumer<RoutingContext, AuthorizationContext> handler);