Java Code Examples for io.vertx.ext.auth.AuthProvider

The following examples show how to use io.vertx.ext.auth.AuthProvider. These examples are extracted from open source projects. 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 Project: besu   Source File: AuthenticationService.java    License: Apache License 2.0 6 votes vote down vote up
private static Optional<AuthenticationService> create(
    final Vertx vertx,
    final boolean authenticationEnabled,
    final String authenticationCredentialsFile,
    final File authenticationPublicKeyFile) {
  if (!authenticationEnabled) {
    return Optional.empty();
  }

  final JWTAuthOptions jwtAuthOptions =
      authenticationPublicKeyFile == null
          ? jwtAuthOptionsFactory.createWithGeneratedKeyPair()
          : jwtAuthOptionsFactory.createForExternalPublicKey(authenticationPublicKeyFile);

  final Optional<AuthProvider> credentialAuthProvider =
      makeCredentialAuthProvider(vertx, authenticationEnabled, authenticationCredentialsFile);

  return Optional.of(
      new AuthenticationService(
          JWTAuth.create(vertx, jwtAuthOptions), jwtAuthOptions, credentialAuthProvider));
}
 
Example 2
Source Project: apiman   Source File: BasicAuth.java    License: Apache License 2.0 6 votes vote down vote up
private static AuthProvider authenticateBasic(JsonObject apimanConfig) {
    return (authInfo, resultHandler) -> {
        String storedUsername = apimanConfig.getString("username");
        String storedPassword = apimanConfig.getString("password");

        if (storedUsername == null || storedPassword == null) {
            resultHandler.handle(Future.failedFuture("Credentials not set in configuration."));
            return;
        }

        String username = authInfo.getString("username");
        String password = StringUtils.chomp(authInfo.getString("password"));

        if (storedUsername.equals(username) && storedPassword.equals(password)) {
            resultHandler.handle(Future.succeededFuture());
        } else {
            resultHandler.handle(Future.failedFuture("No such user, or password incorrect."));
        }
    };
}
 
Example 3
Source Project: vertx-shell   Source File: ShellAuth.java    License: Apache License 2.0 6 votes vote down vote up
static AuthProvider load(Vertx vertx, JsonObject config) {
  ServiceLoader<ShellAuth> loader = ServiceLoader.load(ShellAuth.class);

  Iterator<ShellAuth> factories = loader.iterator();

  while (factories.hasNext()) {
    try {
      // might fail to start (missing classes for example...
      ShellAuth auth = factories.next();
      if (auth != null) {
        if (auth.provider().equals(config.getString("provider", ""))) {
          return auth.create(vertx, config);
        }
      }
    } catch (RuntimeException e) {
      // continue...
    }
  }
  throw new VertxException("Provider not found [" + config.getString("provider", "") + "] / check your classpath");
}
 
Example 4
Source Project: vertx-shell   Source File: MongoShellAuth.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthProvider create(Vertx vertx, JsonObject config) {
  final MongoAuthOptions options = new MongoAuthOptions(config);
  MongoClient client;
  if (options.getShared()) {
    String datasourceName = options.getDatasourceName();
    if (datasourceName != null) {
      client = MongoClient.createShared(vertx, options.getConfig(), datasourceName);
    } else {
      client = MongoClient.createShared(vertx, options.getConfig());
    }
  } else {
    client = MongoClient.create(vertx, options.getConfig());
  }

  JsonObject authConfig = new JsonObject();
  MongoAuthOptionsConverter.toJson(options, authConfig);
  return MongoAuth.create(client, authConfig);
}
 
Example 5
Source Project: vertx-shell   Source File: HttpTermServerBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExternalAuthProviderFails(TestContext context) throws Exception {
  AtomicInteger count = new AtomicInteger();
  AuthProvider authProvider = (authInfo, resultHandler) -> {
    count.incrementAndGet();
    resultHandler.handle(Future.failedFuture("not authenticated"));
  };
  Async async = context.async();
  server = createServer(context, new HttpTermOptions().setPort(8080));
  server.authProvider(authProvider);
  server.termHandler(term -> {
    context.fail();
  });
  server.listen(context.asyncAssertSuccess(server -> {
    HttpClient client = vertx.createHttpClient();
    WebSocketConnectOptions options = new WebSocketConnectOptions()
      .setPort(8080)
      .setURI(basePath + "/shell/websocket")
      .addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes()));
    client.webSocket(options, context.asyncAssertFailure(ws -> {
      assertEquals(1, count.get());
      async.complete();
    }));
  }));
}
 
Example 6
Source Project: nubes   Source File: AuthenticationFactory.java    License: Apache License 2.0 6 votes vote down vote up
public Handler<RoutingContext> create(Auth auth) {
  final AuthProvider authProvider = config.getAuthProvider();
  if (authProvider == null) {
    return null;
  }
  final AuthMethod authMethod = auth.method();
  Function<AuthProvider, Handler<RoutingContext>> authHandlerCreator = authHandlers.get(authMethod);
  if (authHandlerCreator == null && authMethod == REDIRECT) {
    final String redirect = auth.redirectURL();
    if ("".equals(redirect)) {
      throw new IllegalArgumentException("You must specify a redirectURL if you're using Redirect Auth");
    }
    return RedirectAuthHandler.create(authProvider, redirect);
  } else if (authHandlerCreator == null) {
    throw new UnsupportedOperationException();
  }
  return authHandlerCreator.apply(authProvider);
}
 
Example 7
Source Project: vertx-web   Source File: RouteToEBServiceHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
private User fakeUser(String username) {
  return new User() {
    @Override public JsonObject attributes() {
      return null;
    }
    @Override public User isAuthorized(Authorization authority, Handler<AsyncResult<java.lang.Boolean>> resultHandler) {
      return null;
    }
    @Override public User isAuthorized(String s, Handler<AsyncResult<Boolean>> handler) {
      return null;
    }
    @Override public User clearCache() {
      return null;
    }
    @Override public JsonObject principal() {
      return new JsonObject().put("username", username);
    }
    @Override public void setAuthProvider(AuthProvider authProvider) { }
  };
}
 
Example 8
Source Project: besu   Source File: AuthenticationService.java    License: Apache License 2.0 5 votes vote down vote up
private AuthenticationService(
    final JWTAuth jwtAuthProvider,
    final JWTAuthOptions jwtAuthOptions,
    final Optional<AuthProvider> credentialAuthProvider) {
  this.jwtAuthProvider = jwtAuthProvider;
  this.jwtAuthOptions = jwtAuthOptions;
  this.credentialAuthProvider = credentialAuthProvider;
}
 
Example 9
Source Project: besu   Source File: AuthenticationService.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<AuthProvider> makeCredentialAuthProvider(
    final Vertx vertx,
    final boolean authenticationEnabled,
    @Nullable final String authenticationCredentialsFile) {
  if (authenticationEnabled && authenticationCredentialsFile != null) {
    return Optional.of(
        new TomlAuthOptions().setTomlPath(authenticationCredentialsFile).createProvider(vertx));
  } else {
    return Optional.empty();
  }
}
 
Example 10
Source Project: festival   Source File: SessionManager.java    License: Apache License 2.0 5 votes vote down vote up
public void registerSessionHandler() throws BeansException {
    SessionStore sessionStore = getOrCreateSessionStore();
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);

    resolveAndSetSessionProperties(sessionHandler);

    AuthProvider authProvider = getAuthProvider();
    if (authProvider != null) {
        sessionHandler.setAuthProvider(authProvider);
    }

    router.route().handler(sessionHandler);
}
 
Example 11
Source Project: festival   Source File: SessionManager.java    License: Apache License 2.0 5 votes vote down vote up
private AuthProvider getAuthProvider() {
    AuthProvider authProvider = null;
    try {
        authProvider = beanFactory.getBean(AuthProvider.class);
    } catch (BeansException e) {
        if (log.isDebugEnabled()) {
            log.debug("no auth provider");
        }
    }
    return authProvider;
}
 
Example 12
Source Project: festival   Source File: AuthConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Singleton
@Named
public AuthProvider authProvider(Vertx vertx) {
    JsonObject config = new JsonObject().put("properties_path", "classpath:vertx-users.properties");
    ShiroAuthOptions options = new ShiroAuthOptions().setType(ShiroAuthRealmType.PROPERTIES).setConfig(config);
    return ShiroAuth.create(vertx, options);
}
 
Example 13
Source Project: festival   Source File: AuthConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Singleton
@Named
public AuthProvider authProvider(Vertx vertx) {
    JsonObject config = new JsonObject().put("properties_path", "classpath:vertx-users.properties");
    ShiroAuthOptions options = new ShiroAuthOptions().setType(ShiroAuthRealmType.PROPERTIES).setConfig(config);
    return ShiroAuth.create(vertx, options);
}
 
Example 14
Source Project: crnk-framework   Source File: VertxSecurityProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<HttpRequestContext> onRequest(Mono<HttpRequestContext> mono) {
    return mono.flatMap(request -> {
        JsonObject jsonObject = new JsonObject();
        jsonObject.put("name", "john doe");
        io.vertx.reactivex.ext.auth.AuthProvider rxAuthProvider = io.vertx.reactivex.ext.auth.AuthProvider.newInstance(authProvider);
        Mono<User> userSingle = RxJava2Adapter.singleToMono(rxAuthProvider.rxAuthenticate(jsonObject));
        return userSingle.doOnNext(user -> request.getQueryContext().setAttribute(USER_CONTEXT_ATTRIBUTE, user)).map(user -> request);
    });
}
 
Example 15
public FormLoginHandlerImpl(AuthProvider authProvider, String usernameParam, String passwordParam, String returnURLParam, String directLoggedInOKURL) {
    super(authProvider, usernameParam, passwordParam, returnURLParam, directLoggedInOKURL);
    this.usernameParam = usernameParam;
    this.passwordParam = passwordParam;
    this.authProvider = (UserAuthProvider) authProvider;
    this.returnURLParam = returnURLParam;
    this.directLoggedInOKURL = directLoggedInOKURL;
}
 
Example 16
Source Project: vertx-swagger   Source File: SwaggerAuthHandlerFactory.java    License: Apache License 2.0 5 votes vote down vote up
private AuthHandler getAuthHandler(String name) {
    AuthHandler authHandler = this.authHandlers.get(name);
    if (authHandler != null) {
        return authHandler;
    }

    AuthProvider authProvider = getAuthProviderFactory().getAuthProviderByName(name);
    if (authProvider == null) {
        return null;
    }

    SecuritySchemeDefinition securityScheme = this.securitySchemes.get(name);
    if(securityScheme != null) {
     switch (securityScheme.getType()) {
         case "apiKey":
             ApiKeyAuthDefinition apiKeyAuthDefinition = (ApiKeyAuthDefinition) securityScheme;
             Location apiKeyLocation = Location.valueOf(apiKeyAuthDefinition.getIn().name());
             authHandler = ApiKeyAuthHandler.create(authProvider, apiKeyLocation, apiKeyAuthDefinition.getName());
             break;
         case "basic":
             authHandler = BasicAuthHandler.create(authProvider);
             break;
         case "oauth2":
             vertxLogger.warn("OAuth2 authentication has not been implemented yet!");
             break;
         default:
             vertxLogger.warn("SecurityScheme is not authorized : " + securityScheme.getType());
             break;
     }
     
	
     if (authHandler != null) {
         this.authHandlers.put(name, authHandler);
     }
    } else {
        vertxLogger.warn("No securityScheme definition in swagger file for auth provider: " + name);
    }

    return authHandler;
}
 
Example 17
Source Project: hono   Source File: ExecutionContextAuthHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private AuthProvider getAuthProvider(final T ctx) {

        final Object obj = ctx.get(AUTH_PROVIDER_CONTEXT_KEY);
        if (obj instanceof AuthProvider) {
            log.debug("using auth provider found in context [type: {}]", obj.getClass().getName());
            // we're overruling the configured one for this request
            return (AuthProvider) obj;
        } else {
            // bad type, ignore and return default
            return authProvider;
        }
    }
 
Example 18
Source Project: hono   Source File: HonoChainAuthHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets up the fixture.
 */
@BeforeEach
public void setUp() {

    authProvider = mock(AuthProvider.class);
    final AuthHandler chainedAuthHandler = new AuthHandlerImpl(authProvider) {

        @Override
        public void parseCredentials(final RoutingContext context, final Handler<AsyncResult<JsonObject>> handler) {
            handler.handle(Future.succeededFuture(new JsonObject()));
        }
    };
    authHandler = new HonoChainAuthHandler();
    authHandler.append(chainedAuthHandler);
}
 
Example 19
Source Project: hono   Source File: HonoBasicAuthHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets up the fixture.
 */
@BeforeEach
public void setUp() {
    authProvider = mock(AuthProvider.class);
    authHandler = new HonoBasicAuthHandler(authProvider, "test", NoopTracerFactory.create()) {

        @Override
        public void parseCredentials(final RoutingContext context, final Handler<AsyncResult<JsonObject>> handler) {
            handler.handle(Future.succeededFuture(new JsonObject()));
        }
    };
}
 
Example 20
Source Project: vertx-shell   Source File: JDBCShellAuth.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AuthProvider create(Vertx vertx, JsonObject config) {
  final JDBCAuthOptions options = new JDBCAuthOptions(config);
  final JDBCClient client;

  if (options.isShared()) {
    String datasourceName = options.getDatasourceName();
    if (datasourceName != null) {
      client = JDBCClient.createShared(vertx, options.getConfig(), datasourceName);
    } else {
      client = JDBCClient.createShared(vertx, options.getConfig());
    }
  } else {
    client = JDBCClient.create(vertx, options.getConfig());
  }

  final JDBCAuth auth = JDBCAuth.create(vertx, client);

  if (options.getAuthenticationQuery() != null) {
    auth.setAuthenticationQuery(options.getAuthenticationQuery());
  }
  if (options.getRolesQuery() != null) {
    auth.setRolesQuery(options.getRolesQuery());
  }
  if (options.getPermissionsQuery() != null) {
    auth.setPermissionsQuery(options.getPermissionsQuery());
  }
  if (options.getRolesPrefix() != null) {
    auth.setRolePrefix(options.getRolesPrefix());
  }
  return auth;
}
 
Example 21
Source Project: nubes   Source File: MVCRoute.java    License: Apache License 2.0 5 votes vote down vote up
private void attachAuthHandler(Router router, Vertx vertx) {
  final AuthProvider authProvider = config.getAuthProvider();
  router.route(httpMethod, path).handler(CookieHandler.create());
  router.route(httpMethod, path).handler(UserSessionHandler.create(authProvider));
  router.route(httpMethod, path).handler(SessionHandler.create(LocalSessionStore.create(vertx)));
  router.route(httpMethod, path).handler(authHandler);
  if (loginRedirect != null && !"".equals(loginRedirect)) {
    router.post(loginRedirect).handler(CookieHandler.create());
    router.post(loginRedirect).handler(BodyHandler.create());
    router.post(loginRedirect).handler(UserSessionHandler.create(authProvider));
    router.post(loginRedirect).handler(SessionHandler.create(LocalSessionStore.create(vertx)));
    router.post(loginRedirect).handler(FormLoginHandler.create(authProvider));
  }
}
 
Example 22
Source Project: vertx-auth   Source File: AuthShiroExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void example4(AuthProvider authProvider) {

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

    authProvider.authenticate(authInfo, res -> {
      if (res.succeeded()) {
        User user = res.result();
      } else {
        // Failed!
      }
    });
  }
 
Example 23
Source Project: vertx-auth   Source File: CreateShiroAuthProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithRealm() {
  Realm realm = new MyShiroRealm();
  AuthProvider authProvider = ShiroAuth.create(vertx, realm);
  JsonObject authInfo = new JsonObject().put("username", "tim").put("password", "sausages");
  authProvider.authenticate(authInfo, onSuccess(user -> {
    assertNotNull(user);
    testComplete();
  }));
  await();
}
 
Example 24
Source Project: besu   Source File: TomlAuthOptions.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public AuthProvider createProvider(final Vertx vertx) {
  return new TomlAuth(vertx, this);
}
 
Example 25
Source Project: besu   Source File: TomlUser.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setAuthProvider(final AuthProvider authProvider) {
  // we only use Toml for authentication
  throw new UnsupportedOperationException("Not implemented");
}
 
Example 26
Source Project: festival   Source File: AuthConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Singleton
@Named
public AuthHandler authHandler(AuthProvider authProvider) {
    return BasicAuthHandler.create(authProvider);
}
 
Example 27
Source Project: festival   Source File: AuthConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Singleton
@Named
public AuthHandler authHandler(AuthProvider authProvider) {
    return BasicAuthHandler.create(authProvider);
}
 
Example 28
Source Project: crnk-framework   Source File: AppModule.java    License: Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
public VertxSecurityProvider securityProvider(AuthProvider authProvider) {
    return new VertxSecurityProvider(authProvider);
}
 
Example 29
Source Project: crnk-framework   Source File: VertxSecurityProvider.java    License: Apache License 2.0 4 votes vote down vote up
public VertxSecurityProvider(AuthProvider authProvider) {
    this.authProvider = authProvider;
}
 
Example 30
Source Project: VX-API-Gateway   Source File: VxApiClientAuthUser.java    License: MIT License 4 votes vote down vote up
@Override
public void setAuthProvider(AuthProvider authProvider) {
}