Search in sources :

Example 36 with SecurityEnvironment

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

the class OidcSupportTest method testOutboundFull.

@Test
void testOutboundFull() {
    String tokenContent = "huhahihohyhe";
    TokenCredential tokenCredential = TokenCredential.builder().token(tokenContent).build();
    Subject subject = Subject.builder().addPublicCredential(TokenCredential.class, tokenCredential).build();
    ProviderRequest providerRequest = Mockito.mock(ProviderRequest.class);
    SecurityContext ctx = Mockito.mock(SecurityContext.class);
    when(ctx.user()).thenReturn(Optional.of(subject));
    when(providerRequest.securityContext()).thenReturn(ctx);
    SecurityEnvironment outboundEnv = SecurityEnvironment.builder().targetUri(URI.create("http://www.example.com:7777")).path("/test").build();
    EndpointConfig endpointConfig = EndpointConfig.builder().build();
    boolean outboundSupported = provider.isOutboundSupported(providerRequest, outboundEnv, endpointConfig);
    assertThat("Outbound should not be supported by default", outboundSupported, is(false));
    OutboundSecurityResponse response = provider.outboundSecurity(providerRequest, outboundEnv, endpointConfig).toCompletableFuture().join();
    assertThat("Disabled target should have empty headers", response.requestHeaders().size(), is(0));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) SecurityContext(io.helidon.security.SecurityContext) TokenCredential(io.helidon.security.providers.common.TokenCredential) Subject(io.helidon.security.Subject) EndpointConfig(io.helidon.security.EndpointConfig) ProviderRequest(io.helidon.security.ProviderRequest) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) Test(org.junit.jupiter.api.Test)

Example 37 with SecurityEnvironment

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

the class GoogleTokenProviderTest method createInboundRequest.

private ProviderRequest createInboundRequest(String headerName, String headerValue) {
    SecurityEnvironment env = SecurityEnvironment.builder().header(headerName, headerValue).build();
    Span secSpan = GlobalTracer.get().buildSpan("security").start();
    SecurityContext context = mock(SecurityContext.class);
    when(context.executorService()).thenReturn(ForkJoinPool.commonPool());
    when(context.tracer()).thenReturn(GlobalTracer.get());
    when(context.tracingSpan()).thenReturn(secSpan.context());
    ProviderRequest mock = mock(ProviderRequest.class);
    when(mock.securityContext()).thenReturn(context);
    when(mock.env()).thenReturn(env);
    return mock;
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) SecurityContext(io.helidon.security.SecurityContext) Span(io.opentracing.Span) ProviderRequest(io.helidon.security.ProviderRequest)

Example 38 with SecurityEnvironment

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

the class GoogleTokenProviderTest method testOutbound.

@Test
public void testOutbound() {
    ProviderRequest outboundRequest = buildOutboundRequest();
    SecurityEnvironment outboundEnv = SecurityEnvironment.builder().targetUri(URI.create("http://localhost:8080/path")).method("GET").build();
    EndpointConfig outboundEp = EndpointConfig.create();
    assertThat("Outbound should be supported", provider.isOutboundSupported(outboundRequest, outboundEnv, outboundEp), is(true));
    OutboundSecurityResponse response = provider.syncOutbound(outboundRequest, outboundEnv, outboundEp);
    List<String> authorization = response.requestHeaders().get("Authorization");
    assertThat(authorization, notNullValue());
    assertThat(authorization.size(), is(1));
    String header = authorization.get(0);
    assertThat(header.toLowerCase(), startsWith("bearer "));
    assertThat(header, endsWith(TOKEN_VALUE));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) EndpointConfig(io.helidon.security.EndpointConfig) ProviderRequest(io.helidon.security.ProviderRequest) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) Test(org.junit.jupiter.api.Test)

Example 39 with SecurityEnvironment

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

the class HeaderAtnProvider method syncOutbound.

@Override
protected OutboundSecurityResponse syncOutbound(ProviderRequest providerRequest, SecurityEnvironment outboundEnv, EndpointConfig outboundEndpointConfig) {
    Optional<Subject> toPropagate;
    if (subjectType == SubjectType.USER) {
        toPropagate = providerRequest.securityContext().user();
    } else {
        toPropagate = providerRequest.securityContext().service();
    }
    // find the target
    var target = outboundConfig.findTargetCustomObject(outboundEnv, HeaderAtnOutboundConfig.class, HeaderAtnOutboundConfig::create, HeaderAtnOutboundConfig::create);
    // we have no target, let's fall back to original behavior
    if (target.isEmpty()) {
        if (outboundTokenHandler != null) {
            return toPropagate.map(Subject::principal).map(Principal::id).map(id -> respond(outboundEnv, outboundTokenHandler, id)).orElseGet(OutboundSecurityResponse::abstain);
        }
        return OutboundSecurityResponse.abstain();
    }
    // we found a target
    HeaderAtnOutboundConfig outboundConfig = target.get();
    TokenHandler tokenHandler = outboundConfig.tokenHandler().orElse(defaultOutboundTokenHandler);
    return outboundConfig.explicitUser().or(() -> toPropagate.map(Subject::principal).map(Principal::id)).map(id -> respond(outboundEnv, tokenHandler, id)).orElseGet(OutboundSecurityResponse::abstain);
}
Also used : OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) ProviderRequest(io.helidon.security.ProviderRequest) Config(io.helidon.config.Config) SubjectType(io.helidon.security.SubjectType) OutboundSecurityProvider(io.helidon.security.spi.OutboundSecurityProvider) SynchronousProvider(io.helidon.security.spi.SynchronousProvider) HashMap(java.util.HashMap) TokenHandler(io.helidon.security.util.TokenHandler) AuthenticationResponse(io.helidon.security.AuthenticationResponse) OutboundConfig(io.helidon.security.providers.common.OutboundConfig) Principal(io.helidon.security.Principal) List(java.util.List) AuthenticationProvider(io.helidon.security.spi.AuthenticationProvider) EndpointConfig(io.helidon.security.EndpointConfig) SecurityEnvironment(io.helidon.security.SecurityEnvironment) OutboundTarget(io.helidon.security.providers.common.OutboundTarget) Map(java.util.Map) Optional(java.util.Optional) Subject(io.helidon.security.Subject) TokenHandler(io.helidon.security.util.TokenHandler) Subject(io.helidon.security.Subject) Principal(io.helidon.security.Principal) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse)

Example 40 with SecurityEnvironment

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

the class HttpDigestAuthProvider method validateDigestAuth.

private AuthenticationResponse validateDigestAuth(String headerValue, SecurityEnvironment env) {
    DigestToken token;
    try {
        token = DigestToken.fromAuthorizationHeader(headerValue.substring(DIGEST_PREFIX.length()), env.method().toLowerCase());
    } catch (HttpAuthException e) {
        LOGGER.log(Level.FINEST, "Failed to process digest token", e);
        return failOrAbstain(e.getMessage());
    }
    // decrypt
    byte[] bytes;
    try {
        bytes = Base64.getDecoder().decode(token.getNonce());
    } catch (IllegalArgumentException e) {
        LOGGER.log(Level.FINEST, "Failed to base64 decode nonce", e);
        // not base 64
        return failOrAbstain("Nonce must be base64 encoded");
    }
    if (bytes.length < 17) {
        return failOrAbstain("Invalid nonce length");
    }
    byte[] salt = new byte[SALT_LENGTH];
    byte[] aesNonce = new byte[AES_NONCE_LENGTH];
    byte[] encryptedBytes = new byte[bytes.length - SALT_LENGTH - AES_NONCE_LENGTH];
    System.arraycopy(bytes, 0, salt, 0, salt.length);
    System.arraycopy(bytes, SALT_LENGTH, aesNonce, 0, aesNonce.length);
    System.arraycopy(bytes, SALT_LENGTH + AES_NONCE_LENGTH, encryptedBytes, 0, encryptedBytes.length);
    Cipher cipher = HttpAuthUtil.cipher(digestServerSecret, salt, aesNonce, Cipher.DECRYPT_MODE);
    try {
        byte[] timestampBytes = cipher.doFinal(encryptedBytes);
        long nonceTimestamp = HttpAuthUtil.toLong(timestampBytes, 0, timestampBytes.length);
        // validate nonce
        if ((System.currentTimeMillis() - nonceTimestamp) > digestNonceTimeoutMillis) {
            return failOrAbstain("Nonce timeout");
        }
    } catch (Exception e) {
        LOGGER.log(Level.FINEST, "Failed to validate nonce", e);
        return failOrAbstain("Invalid nonce value");
    }
    // validate realm
    if (!realm.equals(token.getRealm())) {
        return failOrAbstain("Invalid realm");
    }
    return userStore.user(token.getUsername()).map(user -> {
        if (token.validateLogin(user)) {
            // yay, correct user and password!!!
            if (subjectType == SubjectType.USER) {
                return AuthenticationResponse.success(buildSubject(user));
            } else {
                return AuthenticationResponse.successService(buildSubject(user));
            }
        } else {
            return failOrAbstain("Invalid username or password");
        }
    }).orElse(failOrAbstain("Invalid username or password"));
}
Also used : Arrays(java.util.Arrays) ProviderRequest(io.helidon.security.ProviderRequest) Random(java.util.Random) Cipher(javax.crypto.Cipher) Level(java.util.logging.Level) SecureRandom(java.security.SecureRandom) AuthenticationProvider(io.helidon.security.spi.AuthenticationProvider) Map(java.util.Map) BigInteger(java.math.BigInteger) Subject(io.helidon.security.Subject) LinkedList(java.util.LinkedList) Config(io.helidon.config.Config) SubjectType(io.helidon.security.SubjectType) SynchronousProvider(io.helidon.security.spi.SynchronousProvider) Logger(java.util.logging.Logger) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Collectors(java.util.stream.Collectors) Principal(io.helidon.security.Principal) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) SecurityResponse(io.helidon.security.SecurityResponse) Base64(java.util.Base64) List(java.util.List) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Role(io.helidon.security.Role) Optional(java.util.Optional) Cipher(javax.crypto.Cipher)

Aggregations

SecurityEnvironment (io.helidon.security.SecurityEnvironment)63 Test (org.junit.jupiter.api.Test)54 ProviderRequest (io.helidon.security.ProviderRequest)46 EndpointConfig (io.helidon.security.EndpointConfig)35 SecurityContext (io.helidon.security.SecurityContext)35 AuthenticationResponse (io.helidon.security.AuthenticationResponse)22 OutboundSecurityResponse (io.helidon.security.OutboundSecurityResponse)20 Subject (io.helidon.security.Subject)18 List (java.util.List)18 Principal (io.helidon.security.Principal)12 TreeMap (java.util.TreeMap)10 SignedJwt (io.helidon.security.jwt.SignedJwt)8 HashMap (java.util.HashMap)7 Locale (java.util.Locale)7 Jwt (io.helidon.security.jwt.Jwt)6 Instant (java.time.Instant)6 Map (java.util.Map)6 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)6 Context (io.grpc.Context)5 Metadata (io.grpc.Metadata)5