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

The following examples show how to use io.vertx.ext.auth.authorization.AuthorizationProvider. 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: WebExamples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void example40(AuthorizationProvider authProvider, Router router) {
  // Need "list_products" authorization to list products
  router.route("/listproducts/*").handler(
    // create the handler that will perform the attestation
    AuthorizationHandler.create(
      // what to attest
      PermissionBasedAuthorization.create("list_products"))
      // where to lookup the authorizations for the user
      .addAuthorizationProvider(authProvider));

  // Only "admin" has access to /private/settings
  router.route("/private/settings/*").handler(
    // create the handler that will perform the attestation
    AuthorizationHandler.create(
      // what to attest
      RoleBasedAuthorization.create("admin"))
      .addAuthorizationProvider(authProvider));
}
 
Example #2
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthoriseNotHasPermission(TestContext should) {
  final Async test = should.async();

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopus").put("password", "secret");

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    final User user = authenticate.result();
    should.assertNotNull(user);
    AuthorizationProvider authz = SqlAuthorization.create(mysql);
    authz.getAuthorizations(user, getAuthorizations -> {
      should.assertTrue(getAuthorizations.succeeded());
      // attest
      should.assertFalse(PermissionBasedAuthorization.create("eat_sandwich").match(user));
      test.complete();
    });
  });
}
 
Example #3
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthoriseHasPermission(TestContext should) {
  final Async test = should.async();

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopus").put("password", "secret");

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    final User user = authenticate.result();
    should.assertNotNull(user);
    AuthorizationProvider authz = SqlAuthorization.create(mysql);
    authz.getAuthorizations(user, getAuthorizations -> {
      should.assertTrue(getAuthorizations.succeeded());
      // attest
      should.assertTrue(PermissionBasedAuthorization.create("commit_code").match(user));
      test.complete();
    });
  });
}
 
Example #4
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthoriseNotHasRole(TestContext should) {
  final Async test = should.async();

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopus").put("password", "secret");

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    final User user = authenticate.result();
    should.assertNotNull(user);
    AuthorizationProvider authz = SqlAuthorization.create(mysql);
    authz.getAuthorizations(user, getAuthorizations -> {
      should.assertTrue(getAuthorizations.succeeded());
      // attest
      should.assertFalse(RoleBasedAuthorization.create("manager").match(user));
      test.complete();
    });
  });
}
 
Example #5
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthoriseHasRole(TestContext should) {
  final Async test = should.async();

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopus").put("password", "secret");

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    final User user = authenticate.result();
    should.assertNotNull(user);
    AuthorizationProvider authz = SqlAuthorization.create(mysql);
    authz.getAuthorizations(user, getAuthorizations -> {
      should.assertTrue(getAuthorizations.succeeded());
      // attest
      should.assertTrue(RoleBasedAuthorization.create("dev").match(user));
      test.complete();
    });
  });
}
 
Example #6
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private AuthorizationProvider createProvider(String id, Authorization authorization) {
  Set<Authorization> _authorizations = new HashSet<>();
  _authorizations.add(authorization);
  return new AuthorizationProvider() {

    @Override
    public String getId() {
      return id;
    }

    @Override
    public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler) {
      user.authorizations().add(getId(), _authorizations);
      handler.handle(Future.succeededFuture());
    }
  };
}
 
Example #7
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 #8
Source File: AuthorizationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizationHandler addAuthorizationProvider(AuthorizationProvider authorizationProvider) {
  Objects.requireNonNull(authorizationProvider);

  this.authorizationProviders.add(authorizationProvider);
  return this;
}
 
Example #9
Source File: AuthHandlerTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
protected void testAuthorization(String username, boolean fail, Authorization authority) throws Exception {
  if (requiresSession()) {
    router.route().handler(BodyHandler.create());
    SessionStore store = getSessionStore();
    router.route().handler(SessionHandler.create(store));
  }
  AuthenticationProvider authNProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties");
  AuthorizationProvider authZProvider = PropertyFileAuthorization.create(vertx, "login/loginusers.properties");

  AuthenticationHandler authNHandler = createAuthHandler(authNProvider);
  router.route().handler(rc -> {
    // we need to be logged in
    if (rc.user() == null) {
      JsonObject authInfo = new JsonObject().put("username", username).put("password", "delicious:sausages");
      authNProvider.authenticate(authInfo, res -> {
        if (res.succeeded()) {
          rc.setUser(res.result());
          rc.next();
        } else {
          rc.fail(res.cause());
        }
      });
    }
  });
  router.route().handler(authNHandler);
  if (authority != null) {
    router.route().handler(AuthorizationHandler.create(authority).addAuthorizationProvider(authZProvider));
  }
  router.route().handler(rc -> rc.response().end());

  testRequest(HttpMethod.GET, "/", fail ? 403: 200, fail? "Forbidden": "OK");
}
 
Example #10
Source File: EventBusBridgeImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public EventBusBridgeImpl(Vertx vertx, AuthorizationProvider authzProvider, SockJSBridgeOptions options, Handler<BridgeEvent> bridgeEventHandler) {
  this.vertx = vertx;
  this.eb = vertx.eventBus();
  this.authzProvider = authzProvider;
  this.inboundPermitted = options.getInboundPermitteds() == null ? new ArrayList<>() : options.getInboundPermitteds();
  this.outboundPermitted = options.getOutboundPermitteds() == null ? new ArrayList<>() : options.getOutboundPermitteds();
  this.maxAddressLength = options.getMaxAddressLength();
  this.maxHandlersPerSocket = options.getMaxHandlersPerSocket();
  this.pingTimeout = options.getPingTimeout();
  this.replyTimeout = options.getReplyTimeout();
  this.bridgeEventHandler = bridgeEventHandler;
}
 
Example #11
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example40_a(AuthorizationProvider authProvider, Router router) {
  // attest that all requests on the route match the required authorization
  router.route().handler(
    // create the handler that will perform the attestation
    AuthorizationHandler.create(
      // what to attest
      PermissionBasedAuthorization.create("can-do-work"))
      // where to lookup the authorizations for the user
      .addAuthorizationProvider(authProvider));
}
 
Example #12
Source File: AuthOAuth2Examples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example13(Vertx vertx) {
  // you would get this config from the keycloak admin console
  JsonObject keycloakJson = new JsonObject()
    .put("realm", "master")
    .put("realm-public-key", "MIIBIjANBgkqhk...wIDAQAB")
    .put("auth-server-url", "http://localhost:9000/auth")
    .put("ssl-required", "external")
    .put("resource", "frontend")
    .put("credentials", new JsonObject()
      .put("secret", "2fbf5e18-b923-4a83-9657-b4ebd5317f60"));

  // Initialize the OAuth2 Library
  OAuth2Auth oauth2 = KeycloakAuth
    .create(vertx, OAuth2FlowType.PASSWORD, keycloakJson);

  // first get a token (authenticate)
  oauth2.authenticate(
    new JsonObject()
      .put("username", "user")
      .put("password", "secret"))
    .onSuccess(user -> {
      // now check for permissions
      AuthorizationProvider authz = KeycloakAuthorization.create();

      authz.getAuthorizations(user)
        .onSuccess(v -> {
          if (
            RoleBasedAuthorization.create("manage-account")
              .setResource("account")
              .match(user)) {
            // this user is authorized to manage its account
          }
        });
    });
}
 
Example #13
Source File: AuthCommonExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example2(User user, AuthorizationProvider authorizationProvider) {
  // load the authorization for the given user:
  authorizationProvider.getAuthorizations(user, res -> {
    if (res.succeeded()) {
      // cache is populated, perform query
      if (PermissionBasedAuthorization.create("printer1234").match(user)) {
        System.out.println("User has the authority");
      } else {
        System.out.println("User does not have the authority");
      }
    }
  });
}
 
Example #14
Source File: AuthCommonExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example3(User user, AuthorizationProvider authorizationProvider) {
  // load the authorization for the given user:
  authorizationProvider.getAuthorizations(user, res -> {
    if (res.succeeded()) {
      // cache is populated, perform query
      if (RoleBasedAuthorization.create("admin").match(user)) {
        System.out.println("User has the authority");
      } else {
        System.out.println("User does not have the authority");
      }
    }
  });
}
 
Example #15
Source File: AuthJWTExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example13(User user) {
  AuthorizationProvider authz = MicroProfileAuthorization.create();

  authz.getAuthorizations(user)
    .onSuccess(v -> {
      // and now we can perform checks as needed
      if (PermissionBasedAuthorization.create("create-report").match(user)) {
        // Yes the user can create reports
      }
    });
}
 
Example #16
Source File: SockJSHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public Router bridge(AuthorizationProvider authorizationProvider, SockJSBridgeOptions bridgeOptions, Handler<BridgeEvent> bridgeEventHandler) {
  return socketHandler(new EventBusBridgeImpl(vertx, authorizationProvider, bridgeOptions, bridgeEventHandler));
}
 
Example #17
Source File: ServiceAuthInterceptor.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
public ServiceAuthInterceptor setAuthorizationProvider(AuthorizationProvider provider) {
  this.authz = provider;
  return this;
}
 
Example #18
Source File: SockJSHandler.java    From vertx-web with Apache License 2.0 2 votes vote down vote up
/**
 * Like {@link io.vertx.ext.web.handler.sockjs.SockJSHandler#bridge(SockJSBridgeOptions)} but specifying a handler
 * that will receive bridge events.
 * @param authorizationProvider authorization provider to be used on the bridge
 * @param bridgeOptions  options to configure the bridge with
 * @param bridgeEventHandler  handler to receive bridge events
 * @return a router to be mounted on an existing router
 */
Router bridge(AuthorizationProvider authorizationProvider, SockJSBridgeOptions bridgeOptions, Handler<BridgeEvent> bridgeEventHandler);
 
Example #19
Source File: AuthorizationHandler.java    From vertx-web with Apache License 2.0 2 votes vote down vote up
/**
 * Adds a provider that shall be used to retrieve the required authorizations for the user to attest.
 * Multiple calls are allowed to retrieve authorizations from many sources.
 *
 * @param authorizationProvider a provider.
 * @return fluent self.
 */
@Fluent
AuthorizationHandler addAuthorizationProvider(AuthorizationProvider authorizationProvider);