Search in sources :

Example 21 with Security

use of io.helidon.security.Security in project helidon by oracle.

the class WebSecurityProgrammaticTest 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(SecurityHandler.create().queryParam("jwt", TokenHandler.builder().tokenHeader("BEARER_TOKEN").tokenPattern(Pattern.compile("bearer (.*)")).build()).queryParam("name", TokenHandler.builder().tokenHeader("NAME_FROM_REQUEST").build()))).get("/noRoles", WebSecurity.secure()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny"), (req, res) -> {
        res.status(Http.Status.INTERNAL_SERVER_ERROR_500);
        res.send("Should not get here, this role doesn't exist");
    }).get("/auditOnly", WebSecurity.audit().auditEventType("unit_test").auditMessageFormat(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));
    baseUri = "http://localhost:" + server.port();
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Security(io.helidon.security.Security) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) TokenHandler(io.helidon.security.util.TokenHandler) MediaType(io.helidon.common.http.MediaType) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Http(io.helidon.common.http.Http) 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) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 22 with Security

use of io.helidon.security.Security in project helidon by oracle.

the class WebSecurityTests method buildClients.

@BeforeAll
static void buildClients() {
    Security security = Security.builder().addProvider(HttpBasicAuthProvider.builder().build()).build();
    securitySetup = WebClient.builder().addService(WebClientSecurity.create(security)).build();
    webClient = WebClient.create();
}
Also used : Security(io.helidon.security.Security) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 23 with Security

use of io.helidon.security.Security in project helidon by oracle.

the class HeaderAtnProviderConfigTest method testProviderService.

@Test
public void testProviderService() {
    String username = "username";
    Security security = Security.create(config.get("security"));
    SecurityContext context = security.contextBuilder("unit-test").env(SecurityEnvironment.builder().header("Authorization", "bearer " + username).build()).build();
    AuthenticationResponse response = context.atnClientBuilder().buildAndGet();
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.SUCCESS));
    assertThat(response.user(), is(not(Optional.empty())));
    response.user().map(Subject::principal).map(Principal::getName).ifPresent(user -> {
        assertThat(user, is(username));
    });
    assertThat(response.service(), is(Optional.empty()));
}
Also used : SecurityContext(io.helidon.security.SecurityContext) Security(io.helidon.security.Security) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Subject(io.helidon.security.Subject) Test(org.junit.jupiter.api.Test)

Example 24 with Security

use of io.helidon.security.Security in project helidon by oracle.

the class TestParent method createNewClient.

protected static WebClient createNewClient(WebClientService... clientServices) {
    Security security = Security.builder().addProvider(HttpBasicAuthProvider.builder().build()).build();
    SecurityContext securityContext = security.createContext("unit-test");
    Context context = Context.builder().id("unit-test").build();
    context.register(securityContext);
    WebClient.Builder builder = WebClient.builder().baseUri("http://localhost:" + webServer.port() + "/greet").config(CONFIG.get("client")).context(context).addMediaSupport(JsonpSupport.create());
    Stream.of(clientServices).forEach(builder::addService);
    return builder.build();
}
Also used : Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) SecurityContext(io.helidon.security.SecurityContext) Security(io.helidon.security.Security) WebClient(io.helidon.webclient.WebClient)

Example 25 with Security

use of io.helidon.security.Security in project helidon by oracle.

the class WebClientSecurity method request.

@Override
public Single<WebClientServiceRequest> request(WebClientServiceRequest request) {
    if ("true".equalsIgnoreCase(request.properties().get(OutboundConfig.PROPERTY_DISABLE_OUTBOUND))) {
        return Single.just(request);
    }
    Context requestContext = request.context();
    // context either from request or create a new one
    Optional<SecurityContext> maybeContext = requestContext.get(SecurityContext.class);
    SecurityContext context;
    if (null == security) {
        if (maybeContext.isEmpty()) {
            return Single.just(request);
        } else {
            context = maybeContext.get();
        }
    } else {
        // we have our own security - we need to use this instance for outbound,
        // so we cannot re-use the context
        context = createContext(request);
    }
    Span span = context.tracer().buildSpan("security:outbound").asChildOf(context.tracingSpan()).start();
    String explicitProvider = request.properties().get(PROVIDER_NAME);
    OutboundSecurityClientBuilder clientBuilder;
    try {
        SecurityEnvironment.Builder outboundEnv = context.env().derive().clearHeaders();
        outboundEnv.method(request.method().name()).path(request.path().toString()).targetUri(request.uri()).headers(request.headers().toMap());
        EndpointConfig.Builder outboundEp = context.endpointConfig().derive();
        Map<String, String> propMap = request.properties();
        for (String name : propMap.keySet()) {
            Optional.ofNullable(request.properties().get(name)).ifPresent(property -> outboundEp.addAtribute(name, property));
        }
        clientBuilder = context.outboundClientBuilder().outboundEnvironment(outboundEnv).outboundEndpointConfig(outboundEp).explicitProvider(explicitProvider);
    } catch (Exception e) {
        traceError(span, e, null);
        throw e;
    }
    return Single.create(clientBuilder.submit().thenApply(providerResponse -> processResponse(request, span, providerResponse)));
}
Also used : Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) SpanContext(io.opentracing.SpanContext) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) Security(io.helidon.security.Security) WebClientServiceRequest(io.helidon.webclient.WebClientServiceRequest) WebClientService(io.helidon.webclient.spi.WebClientService) Tracer(io.opentracing.Tracer) Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) UUID(java.util.UUID) Logger(java.util.logging.Logger) OutboundSecurityClientBuilder(io.helidon.security.OutboundSecurityClientBuilder) OutboundConfig(io.helidon.security.providers.common.OutboundConfig) WebClientRequestHeaders(io.helidon.webclient.WebClientRequestHeaders) Contexts(io.helidon.common.context.Contexts) Tags(io.opentracing.tag.Tags) SpanContext(io.opentracing.SpanContext) List(java.util.List) EndpointConfig(io.helidon.security.EndpointConfig) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Map(java.util.Map) Optional(java.util.Optional) Single(io.helidon.common.reactive.Single) Span(io.opentracing.Span) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Span(io.opentracing.Span) SecurityContext(io.helidon.security.SecurityContext) OutboundSecurityClientBuilder(io.helidon.security.OutboundSecurityClientBuilder) EndpointConfig(io.helidon.security.EndpointConfig)

Aggregations

Security (io.helidon.security.Security)48 SecurityContext (io.helidon.security.SecurityContext)25 Config (io.helidon.config.Config)22 BeforeAll (org.junit.jupiter.api.BeforeAll)14 Test (org.junit.jupiter.api.Test)14 LogConfig (io.helidon.common.LogConfig)13 Routing (io.helidon.webserver.Routing)12 Optional (java.util.Optional)12 WebSecurity (io.helidon.security.integration.webserver.WebSecurity)10 WebClientSecurity (io.helidon.webclient.security.WebClientSecurity)10 WebServer (io.helidon.webserver.WebServer)10 Channel (io.grpc.Channel)7 GrpcRouting (io.helidon.grpc.server.GrpcRouting)7 GrpcServerConfiguration (io.helidon.grpc.server.GrpcServerConfiguration)7 ServiceDescriptor (io.helidon.grpc.server.ServiceDescriptor)7 Set (java.util.Set)7 CoreMatchers.is (org.hamcrest.CoreMatchers.is)7 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)7 Context (io.helidon.common.context.Context)6 AuthorizationResponse (io.helidon.security.AuthorizationResponse)6