io.vertx.ext.auth.authentication.AuthenticationProvider Java Examples

The following examples show how to use io.vertx.ext.auth.authentication.AuthenticationProvider. 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: CustomAuthHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private AuthenticationHandler newAuthHandler(AuthenticationProvider authProvider, Handler<Throwable> exceptionProcessor) {
  return new AuthenticationHandlerImpl(authProvider) {

    @Override
    public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) {
      handler.handle(Future.succeededFuture(JsonObject::new));
    }

    @Override
    public void processException(RoutingContext ctx, Throwable exception) {
      if (exceptionProcessor != null) {
          exceptionProcessor.handle(exception);
      }
      super.processException(ctx, exception);
    }
  };
}
 
Example #2
Source File: MySQLTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateBadPassword(TestContext should) {
  final Async test = should.async();

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

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

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.failed());
    should.assertNull(authenticate.result());
    should.assertEquals("Invalid username/password", authenticate.cause().getMessage());
    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 testAuthenticate(TestContext should) {
  final Async test = should.async();

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

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

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.succeeded());
    should.assertNotNull(authenticate.result());
    should.assertEquals("lopus", authenticate.result().principal().getString("username"));
    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 testAuthenticateBadUser(TestContext should) {
  final Async test = should.async();

  AuthenticationProvider authn = SqlAuthentication.create(mysql);

  JsonObject authInfo = new JsonObject();
  authInfo.put("username", "lopes").put("password", "s3cr3t");

  authn.authenticate(authInfo, authenticate -> {
    should.assertTrue(authenticate.failed());
    should.assertNull(authenticate.result());
    should.assertEquals("Invalid username/password", authenticate.cause().getMessage());
    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: 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 #7
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 #8
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 #9
Source File: AuthCommonExamples.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
public void example1(AuthenticationProvider authProvider) {

    JsonObject authInfo = new JsonObject()
      .put("username", "tim").put("password", "mypassword");

    authProvider.authenticate(authInfo, res -> {
      if (res.succeeded()) {

        User user = res.result();

        System.out.println("User " + user.principal() + " is now authenticated");

      } else {
        res.cause().printStackTrace();
      }
    });
  }
 
Example #10
Source File: WebExamples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void example63(Router router, AuthenticationProvider provider) {

    ChainAuthHandler chain = ChainAuthHandler.any();

    // add http basic auth handler to the chain
    chain.add(BasicAuthHandler.create(provider));
    // add form redirect auth handler to the chain
    chain.add(RedirectAuthHandler.create(provider));

    // secure your route
    router.route("/secure/resource").handler(chain);
    // your app
    router.route("/secure/resource").handler(ctx -> {
      // do something...
    });
  }
 
Example #11
Source File: CustomAuthHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCredentialsValidationErrorPropagation() throws Exception {

  Handler<RoutingContext> handler = rc -> {
    fail("should not get here");
    rc.response().end("Welcome to the protected resource!");
  };

  Throwable rootCause = new IllegalArgumentException("validation of credentials failed");
  AuthenticationProvider authProvider = mock(AuthenticationProvider.class);
  doAnswer(invocation -> {
    final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1);
    resultHandler.handle(Future.failedFuture(rootCause));
    return null;
  }).when(authProvider).authenticate(any(Credentials.class), any(Handler.class));

  router.route("/protected/*").handler(newAuthHandler(authProvider, exception -> {
    assertTrue(exception instanceof HttpStatusException);
    assertEquals(rootCause, exception.getCause());
  }));

  router.route("/protected/somepage").handler(handler);

  testRequest(HttpMethod.GET, "/protected/somepage", 401, "Unauthorized");
}
 
Example #12
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void addLoginHandler(Router router, AuthenticationProvider authProvider) {
  router.route("/eventbus/*").handler(rc -> {
    // we need to be logged in
    if (rc.user() == null) {
      JsonObject authInfo = new JsonObject().put("username", "tim").put("password", "delicious:sausages");
      authProvider.authenticate(authInfo, res -> {
        if (res.succeeded()) {
          rc.setUser(res.result());
          rc.next();
        } else {
          rc.fail(res.cause());
        }
      });
    }
  });
}
 
Example #13
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendRequiresAuthorityHasnotAuthority() throws Exception {
  sockJSHandler.bridge(defaultOptions.addInboundPermitted(new PermittedOptions().setAddress(addr).setRequiredAuthority("pick_nose")));
  router.clear();
  SessionStore store = LocalSessionStore.create(vertx);
  router.route().handler(SessionHandler.create(store));
  AuthenticationProvider authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties");
  addLoginHandler(router, authProvider);
  router.route("/eventbus/*").handler(sockJSHandler);
  testError(new JsonObject().put("type", "send").put("address", addr).put("body", "foo"), "access_denied");
}
 
Example #14
Source File: AuthSqlExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example5(Vertx vertx, SqlClient sqlClient) {

    SqlAuthenticationOptions options = new SqlAuthenticationOptions();
    // SQL client can be any of the known implementations
    // *. Postgres
    // *. MySQL
    // *. etc...
    AuthenticationProvider authenticationProvider =
      SqlAuthentication.create(sqlClient, options);
  }
 
Example #15
Source File: CustomAuthHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testHttpStatusExceptionFailurePropagation() throws Exception {

  Handler<RoutingContext> handler = rc -> {
    fail("should not get here");
    rc.response().end("Welcome to the protected resource!");
  };

  Throwable rootCause = new HttpStatusException(499, "bla");
  AuthenticationProvider authProvider = mock(AuthenticationProvider.class);
  doAnswer(invocation -> {
    final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1);
    resultHandler.handle(Future.failedFuture(rootCause));
    return null;
  }).when(authProvider).authenticate(any(Credentials.class), any(Handler.class));

  router.route("/protected/*").handler(newAuthHandler(authProvider, exception -> {
    assertTrue(exception instanceof HttpStatusException);
    assertEquals(rootCause, exception);
  }));

  router.route("/protected/somepage").handler(handler);

  router.errorHandler(499, rc -> rc
    .response()
    .setStatusCode(((HttpStatusException)rc.failure()).getStatusCode())
    .setStatusMessage(((HttpStatusException)rc.failure()).getPayload())
    .end()
  );

  testRequest(HttpMethod.GET, "/protected/somepage", 499, "bla");
}
 
Example #16
Source File: RouterFactorySecurityTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private AuthenticationHandler mockFailingAuthHandler(Handler<RoutingContext> mockHandler) {
  return new AuthenticationHandlerImpl<AuthenticationProvider>((authInfo, resultHandler) -> resultHandler.handle(Future.succeededFuture(User.create(new JsonObject())))) {
    @Override
    public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) {
      mockHandler.handle(context);
      handler.handle(Future.failedFuture(new HttpStatusException(401)));
    }
  };
}
 
Example #17
Source File: RouterFactorySecurityTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private AuthenticationHandler mockSuccessfulAuthHandler(Handler<RoutingContext> mockHandler) {
  return new AuthenticationHandlerImpl<AuthenticationProvider>((authInfo, resultHandler) -> resultHandler.handle(Future.succeededFuture(User.create(new JsonObject())))) {
    @Override
    public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) {
      mockHandler.handle(context);
      handler.handle(Future.succeededFuture(JsonObject::new));
    }
  };
}
 
Example #18
Source File: AuthSqlExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example6(AuthenticationProvider authProvider) {

    JsonObject authInfo = new JsonObject()
      .put("username", "tim")
      .put("password", "sausages");

    authProvider.authenticate(authInfo)
      .onSuccess(user -> System.out.println("User: " + user.principal()))
      .onFailure(err -> {
        // Failed!
      });
  }
 
Example #19
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 #20
Source File: BasicAuthHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurityBypass() throws Exception {

  Handler<RoutingContext> handler = rc -> {
    fail("should not get here");
    rc.response().end("Welcome to the protected resource!");
  };

  AuthenticationProvider authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties");
  router.route().pathRegex("/api/.*").handler(BasicAuthHandler.create(authProvider));

  router.route("/api/v1/standard-job-profiles").handler(handler);

  testRequest(HttpMethod.GET, "//api/v1/standard-job-profiles", 401, "Unauthorized");
}
 
Example #21
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendRequiresAuthorityHasAuthority() throws Exception {
  sockJSHandler.bridge(PropertyFileAuthorization.create(vertx, "login/loginusers.properties"), defaultOptions.addInboundPermitted(new PermittedOptions().setAddress(addr).setRequiredAuthority("bang_sticks")), null);
  router.clear();
  SessionStore store = LocalSessionStore.create(vertx);
  router.route().handler(SessionHandler.create(store));
  AuthenticationProvider authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties");
  addLoginHandler(router, authProvider);
  router.route("/eventbus/*").handler(sockJSHandler);
  testSend("foo");
}
 
Example #22
Source File: AuthenticationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
protected AuthenticationProvider getAuthProvider(RoutingContext ctx) {
  try {
    AuthenticationProvider provider = ctx.get(AUTH_PROVIDER_CONTEXT_KEY);
    if (provider != null) {
      // we're overruling the configured one for this request
      return provider;
    }
  } catch (RuntimeException e) {
    // bad type, ignore and return default
  }

  return authProvider;
}
 
Example #23
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private AuthenticationProvider getAuthProvider(RoutingContext ctx) {
  try {
    AuthenticationProvider provider = ctx.get(AUTH_PROVIDER_CONTEXT_KEY);
    if (provider != null) {
      // we're overruling the configured one for this request
      return provider;
    }
  } catch (RuntimeException e) {
    // bad type, ignore and return default
  }

  return authProvider;
}
 
Example #24
Source File: FormLoginHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public FormLoginHandlerImpl(AuthenticationProvider authProvider, String usernameParam, String passwordParam,
                            String returnURLParam, String directLoggedInOKURL) {
  this.authProvider = authProvider;
  this.usernameParam = usernameParam;
  this.passwordParam = passwordParam;
  this.returnURLParam = returnURLParam;
  this.directLoggedInOKURL = directLoggedInOKURL;
}
 
Example #25
Source File: AuthJDBCExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example6(AuthenticationProvider authProvider) {

    JsonObject authInfo = new JsonObject()
      .put("username", "tim")
      .put("password", "sausages");

    authProvider.authenticate(authInfo)
      .onSuccess(user -> {
        System.out.println("User: " + user.principal());
      })
      .onFailure(err -> {
        // Failed!
      });
  }
 
Example #26
Source File: AuthCommonExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example7(Vertx vertx, AuthenticationProvider ldapAuthProvider, AuthenticationProvider propertiesAuthProvider) {
  // users will be checked on the 2 providers
  // and on the first success the operation completes
  ChainAuth.any()
    .add(ldapAuthProvider)
    .add(propertiesAuthProvider);
}
 
Example #27
Source File: AuthCommonExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example8(Vertx vertx, AuthenticationProvider ldapAuthProvider, AuthenticationProvider propertiesAuthProvider) {
  // users will be checked on the 2 providers
  // and on all providers success the operation completes
  ChainAuth.all()
    .add(ldapAuthProvider)
    .add(propertiesAuthProvider);
}
 
Example #28
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example39(Vertx vertx, AuthenticationProvider authProvider, Router router) {

    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));

    // All requests to paths starting with '/private/' will be protected
    router
      .route("/private/*")
      .handler(RedirectAuthHandler.create(authProvider));

    // Handle the actual login
    // One of your pages must POST form login data
    router.post("/login").handler(FormLoginHandler.create(authProvider));

    // Set a static server to serve static resources, e.g. the login page
    router.route().handler(StaticHandler.create());

    router
      .route("/someotherpath")
      .handler(ctx -> {
        // This will be public access - no login required
      });

    router
      .route("/private/somepath")
      .handler(ctx -> {

        // This will require a login

        // This will have the value true
        boolean isAuthenticated = ctx.user() != null;

      });

  }
 
Example #29
Source File: AuthJWTExamples.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public void example6(Vertx vertx) {

    JWTAuthOptions config = new JWTAuthOptions()
      .setKeyStore(new KeyStoreOptions()
        .setPath("keystore.jceks")
        .setPassword("secret"));

    AuthenticationProvider provider = JWTAuth.create(vertx, config);
  }
 
Example #30
Source File: SecuredServerConnectionTest.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext context) {
  vertx = rule.vertx();
  AuthenticationProvider provider = PropertyFileAuthentication.create(vertx, "test-auth.properties");
  server = StompServer.create(vertx, new StompServerOptions().setSecured(true))
      .handler(StompServerHandler.create(vertx).authProvider(provider))
      .listen(context.asyncAssertSuccess());
}