io.vertx.ext.auth.AuthProvider Java Examples

The following examples show how to use io.vertx.ext.auth.AuthProvider. 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: AuthenticationService.java    From besu with 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 File: BasicAuth.java    From apiman with 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 File: ShellAuth.java    From vertx-shell with 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 File: MongoShellAuth.java    From vertx-shell with 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 File: HttpTermServerBase.java    From vertx-shell with 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 File: AuthenticationFactory.java    From nubes with 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 File: RouteToEBServiceHandlerTest.java    From vertx-web with 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 File: HonoChainAuthHandlerTest.java    From hono with 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 #9
Source File: AuthenticationService.java    From besu with 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 File: AuthenticationService.java    From besu with 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 #11
Source File: SessionManager.java    From festival with 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 #12
Source File: SessionManager.java    From festival with 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 #13
Source File: AuthConfig.java    From festival with 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 File: AuthShiroExamples.java    From vertx-auth with 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 #15
Source File: AuthConfig.java    From festival with 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 #16
Source File: VertxSecurityProvider.java    From crnk-framework with 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 #17
Source File: FormLoginHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: MVCRoute.java    From nubes with 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 #19
Source File: JDBCShellAuth.java    From vertx-shell with 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 #20
Source File: SwaggerAuthHandlerFactory.java    From vertx-swagger with 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 #21
Source File: HonoBasicAuthHandlerTest.java    From hono with 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 #22
Source File: ExecutionContextAuthHandler.java    From hono with 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 #23
Source File: CreateShiroAuthProviderTest.java    From vertx-auth with 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 File: DeviceServiceConfiguration.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Autowired
@Bean
public AuthProvider authProvider(final Tracer tracer, final RestEndpointConfiguration restEndpointConfiguration) {
    return new DeviceRegistryTokenAuthProvider(tracer, restEndpointConfiguration.getAuthTokenCacheExpiration());
}
 
Example #25
Source File: ExecutionContextAuthHandler.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public final AuthProvider getAuthProvider() {
    return authProvider;
}
 
Example #26
Source File: ShiroAuthOptions.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
@Override
public AuthProvider createProvider(Vertx vertx) {
  return ShiroAuth.create(vertx, this);
}
 
Example #27
Source File: DeviceServiceConfiguration.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Bean
public AuthProvider authProvider(final Tracer tracer, final RestEndpointConfiguration restEndpointConfiguration) {
    return new DeviceRegistryTokenAuthProvider(tracer, restEndpointConfiguration.getAuthTokenCacheExpiration());
}
 
Example #28
Source File: HttpTermServer.java    From vertx-shell with Apache License 2.0 4 votes vote down vote up
@Override
public TermServer authProvider(AuthProvider provider) {
  authProvider = provider;
  return this;
}
 
Example #29
Source File: DeviceRegistryTokenAuthHandler.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public DeviceRegistryTokenAuthHandler(final Tracer tracer, final AuthProvider authProvider) {
    super(authProvider);
    this.tracer = tracer;
}
 
Example #30
Source File: SSHServer.java    From vertx-shell with Apache License 2.0 4 votes vote down vote up
@Override
public TermServer authProvider(AuthProvider provider) {
  authProvider = provider;
  return this;
}