Search in sources :

Example 31 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class IdcsMain method main.

/**
 * Start the example.
 *
 * @param args ignored
 */
public static void main(String[] args) {
    // load logging configuration
    LogConfig.configureRuntime();
    Config config = buildConfig();
    Security security = Security.create(config.get("security"));
    // this is needed for proper encryption/decryption of cookies
    Contexts.globalContext().register(security);
    Routing.Builder routing = Routing.builder().register(WebSecurity.create(security, config.get("security"))).register(OidcSupport.create(config)).get("/rest/profile", (req, res) -> {
        Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
        res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
        res.send("Response from config based service, you are: \n" + securityContext.flatMap(SecurityContext::user).map(Subject::toString).orElse("Security context is null"));
    }).get("/loggedout", (req, res) -> res.send("You have been logged out"));
    theServer = WebServer.create(routing, config.get("server"));
    IdcsUtil.start(theServer);
}
Also used : Security(io.helidon.security.Security) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) Contexts(io.helidon.common.context.Contexts) MediaType(io.helidon.common.http.MediaType) ConfigSources.file(io.helidon.config.ConfigSources.file) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) Subject(io.helidon.security.Subject) OidcSupport(io.helidon.security.providers.oidc.OidcSupport) ConfigSources.classpath(io.helidon.config.ConfigSources.classpath) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) Optional(java.util.Optional) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing) Security(io.helidon.security.Security) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) Subject(io.helidon.security.Subject)

Example 32 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class MetricsIT method startGrpcServer.

// ----- helper methods -------------------------------------------------
/**
 * Start the gRPC Server listening on an ephemeral port.
 *
 * @throws Exception in case of an error
 */
private static void startGrpcServer() throws Exception {
    // Add the EchoService and enable GrpcMetrics
    GrpcRouting routing = GrpcRouting.builder().intercept(GrpcMetrics.timed()).register(new EchoService(), rules -> rules.intercept(GrpcMetrics.metered()).intercept("Echo", GrpcMetrics.counted())).build();
    // Run the server on port 0 so that it picks a free ephemeral port
    GrpcServerConfiguration serverConfig = GrpcServerConfiguration.builder().port(0).build();
    grpcServer = GrpcServer.create(serverConfig, routing).start().toCompletableFuture().get(10, TimeUnit.SECONDS);
    LOGGER.info("Started gRPC server at: localhost:" + grpcServer.port());
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) WebClient(io.helidon.webclient.WebClient) JsonValue(jakarta.json.JsonValue) Channel(io.grpc.Channel) MediaType(io.helidon.common.http.MediaType) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) AfterAll(org.junit.jupiter.api.AfterAll) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) JsonStructure(jakarta.json.JsonStructure) BeforeAll(org.junit.jupiter.api.BeforeAll) MetricsSupport(io.helidon.metrics.MetricsSupport) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LogConfig(io.helidon.common.LogConfig) EchoServiceGrpc(io.helidon.grpc.server.test.EchoServiceGrpc) GrpcServerConfiguration(io.helidon.grpc.server.GrpcServerConfiguration) Echo(io.helidon.grpc.server.test.Echo) Logger(java.util.logging.Logger) GrpcRouting(io.helidon.grpc.server.GrpcRouting) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) ManagedChannelBuilder(io.grpc.ManagedChannelBuilder) WebServer(io.helidon.webserver.WebServer) GrpcServer(io.helidon.grpc.server.GrpcServer) Routing(io.helidon.webserver.Routing) EchoService(services.EchoService) GrpcServerConfiguration(io.helidon.grpc.server.GrpcServerConfiguration) EchoService(services.EchoService) GrpcRouting(io.helidon.grpc.server.GrpcRouting)

Example 33 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class GraphQlCdiExtension method registerWithWebServer.

void registerWithWebServer(@Observes @Priority(LIBRARY_BEFORE + 9) @Initialized(ApplicationScoped.class) Object event, BeanManager bm) {
    Config config = ConfigProvider.getConfig();
    // this works for Helidon MP config
    io.helidon.config.Config graphQlConfig = ((io.helidon.config.Config) config).get("graphql");
    InvocationHandler.Builder handlerBuilder = InvocationHandler.builder().config(graphQlConfig).schema(createSchema());
    config.getOptionalValue(ConfigKey.DEFAULT_ERROR_MESSAGE, String.class).ifPresent(handlerBuilder::defaultErrorMessage);
    config.getOptionalValue(ConfigKey.EXCEPTION_WHITE_LIST, String[].class).ifPresent(handlerBuilder::exceptionWhitelist);
    config.getOptionalValue(ConfigKey.EXCEPTION_BLACK_LIST, String[].class).ifPresent(handlerBuilder::exceptionBlacklist);
    GraphQlSupport graphQlSupport = GraphQlSupport.builder().config(graphQlConfig).invocationHandler(handlerBuilder).build();
    try {
        ServerCdiExtension server = bm.getExtension(ServerCdiExtension.class);
        Optional<String> routingNameConfig = config.getOptionalValue("graphql.routing", String.class);
        Routing.Builder routing = routingNameConfig.stream().filter(Predicate.not("@default"::equals)).map(server::serverNamedRoutingBuilder).findFirst().orElseGet(server::serverRoutingBuilder);
        graphQlSupport.update(routing);
    } catch (Throwable e) {
        LOGGER.log(Level.WARNING, "Failed to set up routing with web server, maybe server extension missing?", e);
    }
}
Also used : Config(org.eclipse.microprofile.config.Config) GraphQlSupport(io.helidon.graphql.server.GraphQlSupport) Routing(io.helidon.webserver.Routing) InvocationHandler(io.helidon.graphql.server.InvocationHandler) ServerCdiExtension(io.helidon.microprofile.server.ServerCdiExtension)

Example 34 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class WebSecurityBuilderGateDefaultsTest method initClass.

@BeforeAll
public static void initClass() throws InterruptedException {
    WebSecurityTestUtil.auditLogFinest();
    myAuditProvider = new UnitTestAuditProvider();
    Config config = Config.create();
    Security security = Security.builder(config.get("security")).addAuditProvider(myAuditProvider).build();
    Routing routing = Routing.builder().register(WebSecurity.create(security).securityDefaults(WebSecurity.rolesAllowed("admin").audit())).get("/noRoles", WebSecurity.enforce()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny")).get("/auditOnly", WebSecurity.enforce().skipAuthentication().skipAuthorization().auditEventType("unit_test").auditMessageFormat(WebSecurityTests.AUDIT_MESSAGE_FORMAT)).get("/{*}", (req, res) -> {
        Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
        res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
        res.send("Hello, you are: \n" + securityContext.map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()).orElse("Security context is null"));
    }).build();
    server = WebServer.create(routing);
    long t = System.currentTimeMillis();
    CountDownLatch cdl = new CountDownLatch(1);
    server.start().thenAccept(webServer -> {
        long time = System.currentTimeMillis() - t;
        System.out.println("Started server on localhost:" + webServer.port() + " in " + time + " millis");
        cdl.countDown();
    });
    // we must wait for server to start, so other tests are not triggered until it is ready!
    assertThat("Timeout while waiting for server to start!", cdl.await(5, TimeUnit.SECONDS), is(true));
    serverBaseUri = "http://localhost:" + server.port();
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Security(io.helidon.security.Security) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) CoreMatchers.not(org.hamcrest.CoreMatchers.not) MediaType(io.helidon.common.http.MediaType) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) AfterAll(org.junit.jupiter.api.AfterAll) AuditEvent(io.helidon.security.AuditEvent) BeforeAll(org.junit.jupiter.api.BeforeAll) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Http(io.helidon.common.http.Http) HttpBasicAuthProvider(io.helidon.security.providers.httpauth.HttpBasicAuthProvider) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Config(io.helidon.config.Config) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) Set(java.util.Set) SecurityContext(io.helidon.security.SecurityContext) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) Routing(io.helidon.webserver.Routing) Optional(java.util.Optional) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing) Security(io.helidon.security.Security) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 35 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class OutboundSecurityIT method startServers.

// ----- test lifecycle methods -----------------------------------------
@BeforeAll
public static void startServers() throws Exception {
    LogConfig.configureRuntime();
    Config config = Config.create();
    Security security = Security.builder().addProvider(HttpBasicAuthProvider.create(config.get("http-basic-auth"))).build();
    // secured web server's Routing
    Routing webRouting = Routing.builder().register(WebSecurity.create(security).securityDefaults(WebSecurity.authenticate())).get("/test", WebSecurity.rolesAllowed("admin"), OutboundSecurityIT::echoWebRequest).get("/propagate", WebSecurity.rolesAllowed("user"), OutboundSecurityIT::propagateCredentialsWebRequest).get("/override", WebSecurity.rolesAllowed("user"), OutboundSecurityIT::overrideCredentialsWebRequest).build();
    webServer = WebServer.create(webRouting).start().toCompletableFuture().get(10, TimeUnit.SECONDS);
    webServerURL = "http://127.0.0.1:" + webServer.port();
    client = ClientBuilder.newBuilder().build().register(HttpAuthenticationFeature.basicBuilder().build());
    ServiceDescriptor echoService = ServiceDescriptor.builder(new SecuredOutboundEchoService(webServerURL)).intercept(GrpcSecurity.rolesAllowed("admin")).build();
    // Add the EchoService
    GrpcRouting grpcRouting = GrpcRouting.builder().intercept(GrpcSecurity.create(security).securityDefaults(GrpcSecurity.authenticate())).register(echoService).build();
    // Run the server on port 0 so that it picks a free ephemeral port
    GrpcServerConfiguration serverConfig = GrpcServerConfiguration.builder().port(0).build();
    grpcServer = GrpcServer.create(serverConfig, grpcRouting).start().toCompletableFuture().get(10, TimeUnit.SECONDS);
    Channel channel = InProcessChannelBuilder.forName(grpcServer.configuration().name()).build();
    adminEchoStub = EchoServiceGrpc.newBlockingStub(channel).withCallCredentials(adminCreds);
    noCredsEchoStub = EchoServiceGrpc.newBlockingStub(channel);
}
Also used : GrpcServerConfiguration(io.helidon.grpc.server.GrpcServerConfiguration) ServiceDescriptor(io.helidon.grpc.server.ServiceDescriptor) LogConfig(io.helidon.common.LogConfig) Config(io.helidon.config.Config) Channel(io.grpc.Channel) GrpcRouting(io.helidon.grpc.server.GrpcRouting) Routing(io.helidon.webserver.Routing) Security(io.helidon.security.Security) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) SecuredOutboundEchoService(services.SecuredOutboundEchoService) GrpcRouting(io.helidon.grpc.server.GrpcRouting) BeforeAll(org.junit.jupiter.api.BeforeAll)

Aggregations

Routing (io.helidon.webserver.Routing)86 WebServer (io.helidon.webserver.WebServer)38 Config (io.helidon.config.Config)33 Test (org.junit.jupiter.api.Test)32 Http (io.helidon.common.http.Http)23 TimeUnit (java.util.concurrent.TimeUnit)21 LogConfig (io.helidon.common.LogConfig)19 MediaType (io.helidon.common.http.MediaType)19 CoreMatchers.is (org.hamcrest.CoreMatchers.is)17 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)17 SecurityContext (io.helidon.security.SecurityContext)16 HttpException (io.helidon.webserver.HttpException)15 Optional (java.util.Optional)15 CountDownLatch (java.util.concurrent.CountDownLatch)15 WebSecurity (io.helidon.security.integration.webserver.WebSecurity)13 SERVICE_UNAVAILABLE_503 (io.helidon.common.http.Http.Status.SERVICE_UNAVAILABLE_503)11 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)11 Security (io.helidon.security.Security)11 StaticContentSupport (io.helidon.webserver.staticcontent.StaticContentSupport)10 TestResponse (io.helidon.webserver.testsupport.TestResponse)10