io.vertx.ext.web.handler.AuthHandler Java Examples

The following examples show how to use io.vertx.ext.web.handler.AuthHandler. 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: XYZHubRESTVerticle.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Add the security handlers.
 */
private AuthHandler createJWTHandler() {
  JWTAuthOptions authConfig = new JWTAuthOptions().addPubSecKey(
      new PubSecKeyOptions().setAlgorithm("RS256")
          .setPublicKey(Service.configuration.JWT_PUB_KEY));

  JWTAuth authProvider = new XyzAuthProvider(vertx, authConfig);

  ChainAuthHandler authHandler = ChainAuthHandler.create()
      .append(JWTAuthHandler.create(authProvider))
      .append(JWTURIHandler.create(authProvider));

  if (Service.configuration.XYZ_HUB_AUTH == AuthorizationType.DUMMY) {
    authHandler.append(JwtDummyHandler.create(authProvider));
  }

  return authHandler;
}
 
Example #2
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
private static AuthHandler getAuthHandler(SwaggerAuthHandlerFactory authHandlerFactory, Swagger swagger, Operation operation) {
    AuthHandler authHandler = null;
    if(authHandlerFactory != null) {
        if(operation.getSecurity() != null) {
        	if(!operation.getSecurity().isEmpty()) {
        		authHandler = authHandlerFactory.createAuthHandler(operation.getSecurity());
        	}
        } else if(swagger.getSecurity() != null && !swagger.getSecurity().isEmpty()) {
            List<Map<String, List<String>>> security = swagger.getSecurity().stream()
                    .map(SecurityRequirement::getRequirements)
                    .collect(Collectors.toList());
            authHandler = authHandlerFactory.createAuthHandler(security);
        }
    }

    return authHandler;
}
 
Example #3
Source File: AuthFactory.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an auth handler of the type indicated in the `auth` section of config.
 *
 * @param vertx the vert.x instance
 * @param router the vert.x web router to protect
 * @param apimanConfig the apiman config
 * @return an auth handler
 */
public static AuthHandler getAuth(Vertx vertx, Router router, VertxEngineConfig apimanConfig) {
    String type = apimanConfig.getAuth().getString("type", "NONE");
    JsonObject authConfig = apimanConfig.getAuth().getJsonObject("config", new JsonObject());

    switch(AuthType.getType(type)) {
    case BASIC:
        return BasicAuth.create(authConfig);
    case NONE:
        return NoneAuth.create();
    case KEYCLOAK:
        return KeycloakOAuthFactory.create(vertx, router, apimanConfig, authConfig);
    default:
        return NoneAuth.create();
    }
}
 
Example #4
Source File: XYZHubRESTVerticle.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> fut) {
  OpenAPI3RouterFactory.create(vertx, CONTRACT_LOCATION, ar -> {
    if (ar.succeeded()) {
      //Add the handlers
      final OpenAPI3RouterFactory routerFactory = ar.result();
      routerFactory.setOptions(new RouterFactoryOptions());
      featureApi = new FeatureApi(routerFactory);
      featureQueryApi = new FeatureQueryApi(routerFactory);
      spaceApi = new SpaceApi(routerFactory);

      final AuthHandler jwtHandler = createJWTHandler();
      routerFactory.addSecurityHandler("authToken", jwtHandler);

      final Router router = routerFactory.getRouter();
      //Add additional handler to the router
      router.route().failureHandler(XYZHubRESTVerticle::failureHandler);
      router.route().order(0)
          .handler(this::onRequestReceived)
          .handler(createCorsHandler());

      this.healthApi = new HealthApi(vertx, router);
      this.adminApi = new AdminApi(vertx, router, jwtHandler);

      //OpenAPI resources
      router.route("/hub/static/openapi/*").handler(createCorsHandler()).handler((routingContext -> {
        final HttpServerResponse res = routingContext.response();
        final String path = routingContext.request().path();
        if (path.endsWith("full.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(FULL_API.getBytes().length));
          res.write(FULL_API);
        } else if (path.endsWith("stable.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(STABLE_API.getBytes().length));
          res.write(STABLE_API);
        } else if (path.endsWith("experimental.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(EXPERIMENTAL_API.getBytes().length));
          res.write(EXPERIMENTAL_API);
        } else if (path.endsWith("contract.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(CONTRACT_API.getBytes().length));
          res.write(CONTRACT_API);
        } else {
          res.setStatusCode(HttpResponseStatus.NOT_FOUND.code());
        }

        res.end();
      }));

      //Static resources
      router.route("/hub/static/*").handler(StaticHandler.create().setIndexPage("index.html")).handler(createCorsHandler());
      if (Service.configuration.FS_WEB_ROOT != null) {
        logger.debug("Serving extra web-root folder in file-system with location: {}", Service.configuration.FS_WEB_ROOT);
        //noinspection ResultOfMethodCallIgnored
        new File(Service.configuration.FS_WEB_ROOT).mkdirs();
        router.route("/hub/static/*")
            .handler(StaticHandler.create(Service.configuration.FS_WEB_ROOT).setIndexPage("index.html"));
      }

      //Default NotFound handler
      router.route().last().handler(XYZHubRESTVerticle::notFoundHandler);

      vertx.createHttpServer(SERVER_OPTIONS)
          .requestHandler(router)
          .listen(
              Service.configuration.HTTP_PORT, result -> {
                if (result.succeeded()) {
                  createMessageServer(router, fut);
                } else {
                  logger.error("An error occurred, during the initialization of the server.", result.cause());
                  fut.fail(result.cause());
                }
              });
    } else {
      logger.error("An error occurred, during the creation of the router from the Open API specification file.", ar.cause());
    }
  });
}
 
Example #5
Source File: AdminApi.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public AdminApi(Vertx vertx, Router router, AuthHandler auth) {
  router.route(HttpMethod.POST, ADMIN_MESSAGES_ENDPOINT)
      .handler(auth)
      .handler(this::onMessage);

  router.route(HttpMethod.POST, ADMIN_EVENTS_ENDPOINT)
      .handler(auth)
      .handler(this::onEvent);
}
 
Example #6
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
private static void configureAuthRoute(Router baseRouter, HttpMethod method, String path, Swagger swagger, Operation operation,
                                       SwaggerAuthHandlerFactory authHandlerFactory) {
    AuthHandler authHandler = getAuthHandler(authHandlerFactory, swagger, operation);
    if(authHandler != null) {
        ROUTE_BUILDERS.get(method).buildRoute(baseRouter, path).handler(authHandler);
    }
}
 
Example #7
Source File: KeycloakOAuthFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
public static AuthHandler create(Vertx vertx, Router router, VertxEngineConfig apimanConfig, JsonObject authConfig) {
    OAuth2FlowType flowType = toEnum(authConfig.getString("flowType"));
    String role = authConfig.getString("requiredRole");

    Objects.requireNonNull(flowType, String.format("flowType must be specified and valid. Flows: %s.", Arrays.asList(OAuth2FlowType.values())));
    Objects.requireNonNull(role, "requiredRole must be non-null.");

    if (flowType != OAuth2FlowType.AUTH_CODE) {
        return directGrant(vertx, apimanConfig, authConfig, flowType, role);
    } else {
        return standardAuth(vertx, router, apimanConfig, authConfig, flowType);
    }
}
 
Example #8
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 #9
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 #10
Source File: Main.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // TODO start a vertx instance
    // deploy verticles / one per resource in this case

    Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    Vertx vertx = Vertx.vertx();

    HttpClientOptions clientOptions = new HttpClientOptions()
            .setSsl(true)
            .setTrustStoreOptions(new JksOptions()
                    .setPath(System.getProperty("javax.net.ssl.trustStore"))
                    .setPassword(System.getProperty("javax.net.ssl.trustStorePassword")));
    HttpClient httpClient = vertx.createHttpClient(clientOptions);

    Router router = Router.router(vertx);
    AuthHandler auth = new BearerAuthHandler(new FacebookOauthTokenVerifier(httpClient));
    router.route("/*").handler(auth);

    HelloResource helloResource = new HelloResource(httpClient);
    router.get("/hello").produces("text/plain").handler(helloResource::hello);

    CarRepository carRepository = new InMemoryCarRepository();
    CarsResource carsResource = new CarsResource(carRepository);
    router.route("/cars*").handler(BodyHandler.create());
    router.get("/cars").produces("application/json").handler(carsResource::all);
    router.post("/cars").consumes("application/json").handler(carsResource::create);

    CarResource carResource = new CarResource(carRepository);
    router.get("/cars/:id").produces("application/json").handler(carResource::byId);

    HttpServerOptions serverOptions = new HttpServerOptions()
            .setSsl(true)
            .setKeyStoreOptions(new JksOptions()
                    .setPath(System.getProperty("javax.net.ssl.keyStorePath"))
                    .setPassword(System.getProperty("javax.net.ssl.keyStorePassword")))
            .setPort(8090);
    HttpServer server = vertx.createHttpServer(serverOptions);
    server.requestHandler(router::accept).listen();
}
 
Example #11
Source File: DeviceServiceConfiguration.java    From enmasse with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an authentication handler used by device registry management HTTP API.
 *
 * @return The handler.
 */
@Autowired
@Bean
public AuthHandler authHandler(final Tracer tracer, final RestEndpointConfiguration restEndpointConfiguration) {
    return new DeviceRegistryTokenAuthHandler(tracer, authProvider(tracer, restEndpointConfiguration));
}
 
Example #12
Source File: ApiVerticle.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) {
    Future<Void> superFuture = Future.future();
    Future<HttpServer> listenFuture = Future.future();
    super.start(superFuture);

    CompositeFuture.all(superFuture, listenFuture)
        .setHandler(compositeResult -> {
            if (compositeResult.succeeded()) {
                startFuture.complete(null);
            } else {
                startFuture.fail(compositeResult.cause());
            }
        });

    VertxResteasyDeployment deployment = new VertxResteasyDeployment();
    deployment.start();

    addResources(deployment.getRegistry(),
            new SystemResourceImpl(apimanConfig, engine),
            new ApiResourceImpl(apimanConfig, engine),
            new ClientResourceImpl(apimanConfig, engine),
            new OrgResourceImpl(apimanConfig, engine));

    deployment.getProviderFactory().register(RestExceptionMapper.class);

    VertxRequestHandler resteasyRh = new VertxRequestHandler(vertx, deployment);

    Router router = Router.router(vertx)
                .exceptionHandler(error -> log.error(error.getMessage(), error));

    // Ensure body handler is attached early so that if AuthHandler takes an external action
    // we don't end up losing the body (e.g OAuth2).
    router.route()
        .handler(BodyHandler.create());

    AuthHandler authHandler = AuthFactory.getAuth(vertx, router, apimanConfig);

    router.route("/*")
        .handler(authHandler);

    router.route("/*") // We did the previous stuff, now we call into JaxRS.
        .handler(context -> resteasyRh.handle(new Router2ResteasyRequestAdapter(context)));

    HttpServerOptions httpOptions = new HttpServerOptions();

    if (apimanConfig.isSSL()) {
        httpOptions.setSsl(true)
        .setKeyStoreOptions(
                new JksOptions()
                    .setPath(apimanConfig.getKeyStore())
                    .setPassword(apimanConfig.getKeyStorePassword())
                )
        .setTrustStoreOptions(
                new JksOptions()
                    .setPath(apimanConfig.getTrustStore())
                    .setPassword(apimanConfig.getTrustStorePassword())
                );
        addAllowedSslTlsProtocols(httpOptions);
    } else {
        log.warn("API is running in plaintext mode. Enable SSL in config for production deployments.");
    }

    vertx.createHttpServer(httpOptions)
        .requestHandler(router::accept)
        .listen(apimanConfig.getPort(VERTICLE_TYPE),
                apimanConfig.getHostname(),
                listenFuture.completer());
}
 
Example #13
Source File: NoneAuth.java    From apiman with Apache License 2.0 4 votes vote down vote up
public static AuthHandler create() {
    return new NoneAuth();
}
 
Example #14
Source File: NoneAuth.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Override
public AuthHandler addAuthorities(Set<String> authorities) {
    return this;
}
 
Example #15
Source File: NoneAuth.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Override
public AuthHandler addAuthority(String authority) {
    return this;
}
 
Example #16
Source File: BasicAuth.java    From apiman with Apache License 2.0 4 votes vote down vote up
public static AuthHandler create(JsonObject apimanConfig) {
    return new BasicAuth(authenticateBasic(apimanConfig), apimanConfig.getString("realm", "apiman-gateway"));
}
 
Example #17
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public AuthHandler addAuthorities(Set<String> authorities) {
  this.authorities.addAll(authorities);
  return this;
}
 
Example #18
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public AuthHandler addAuthority(String authority) {
  authorities.add(authority);
  return this;
}
 
Example #19
Source File: AuthConfig.java    From festival with Apache License 2.0 4 votes vote down vote up
@Singleton
@Named
public AuthHandler authHandler(AuthProvider authProvider) {
    return BasicAuthHandler.create(authProvider);
}
 
Example #20
Source File: ApiKeyAuthHandler.java    From vertx-swagger with Apache License 2.0 4 votes vote down vote up
public static AuthHandler create(AuthProvider authProvider, ApiKeyAuthHandler.Location location,
        String name) {
    return new ApiKeyAuthHandler(authProvider, location, name);
}
 
Example #21
Source File: AuthConfig.java    From festival with Apache License 2.0 4 votes vote down vote up
@Singleton
@Named
public AuthHandler authHandler(AuthProvider authProvider) {
    return BasicAuthHandler.create(authProvider);
}
 
Example #22
Source File: ApplicationConfig.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new instance of an auth handler to provide basic authentication for the 
 * HTTP based Device Registry Management endpoint.
 * <p>
 * This creates an instance of the {@link HonoBasicAuthHandler} with an auth provider of type
 * {@link MongoAuth} if the property corresponding to {@link HttpServiceConfigProperties#isAuthenticationRequired()}
 * is set to {@code true}.
 *
 * @param httpServiceConfigProperties The properties for configuring the HTTP based device registry
 *                                    management endpoint.
 * @return The auth handler if the {@link HttpServiceConfigProperties#isAuthenticationRequired()} 
 *         is {@code true} or {@code null} otherwise.
 * @see <a href="https://vertx.io/docs/vertx-auth-mongo/java/">Mongo auth provider docs</a>
 */
@Bean
@Scope("prototype")
public AuthHandler createAuthHandler(final HttpServiceConfigProperties httpServiceConfigProperties) {
    if (httpServiceConfigProperties != null && httpServiceConfigProperties.isAuthenticationRequired()) {
        return new HonoBasicAuthHandler(
                MongoAuth.create(mongoClient(), new JsonObject()),
                httpServerProperties().getRealm(),
                getTracer());
    }
    return null;
}
 
Example #23
Source File: DeviceServiceConfiguration.java    From enmasse with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an authentication handler used by device registry management HTTP API.
 *
 * @return The handler.
 */
@Bean
public AuthHandler authHandler(final Tracer tracer, final RestEndpointConfiguration restEndpointConfiguration) {
    return new DeviceRegistryTokenAuthHandler(tracer, authProvider(tracer, restEndpointConfiguration));
}
 
Example #24
Source File: HttpServiceBase.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Sets auth handler.
 *
 * @param authHandler The handler.
 */
@Autowired(required = false)
public void setAuthHandler(final AuthHandler authHandler) {
    this.authHandler = authHandler;
}