Search in sources :

Example 1 with SecurityException

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

the class IdcsMtRoleMapperRxProvider method getGrantsFromServer.

/**
 * Get grants from IDCS server. The result is cached.
 *
 * @param idcsTenantId ID of the IDCS tenant
 * @param idcsAppName  Name of IDCS application
 * @param subject      subject to get grants for
 * @return optional list of grants from server
 */
protected Single<List<? extends Grant>> getGrantsFromServer(String idcsTenantId, String idcsAppName, Subject subject) {
    String subjectName = subject.principal().getName();
    String subjectType = (String) subject.principal().abacAttribute("sub_type").orElse(defaultIdcsSubjectType());
    RoleMapTracing tracing = SecurityTracing.get().roleMapTracing("idcs");
    return Single.create(getAppToken(idcsTenantId, tracing)).flatMapSingle(maybeAppToken -> {
        if (maybeAppToken.isEmpty()) {
            return Single.error(new SecurityException("Application token not available"));
        }
        return Single.just(maybeAppToken.get());
    }).flatMapSingle(appToken -> {
        JsonObjectBuilder requestBuilder = JSON.createObjectBuilder().add("mappingAttributeValue", subjectName).add("subjectType", subjectType).add("appName", idcsAppName).add("includeMemberships", true);
        JsonArrayBuilder arrayBuilder = JSON.createArrayBuilder();
        arrayBuilder.add("urn:ietf:params:scim:schemas:oracle:idcs:Asserter");
        requestBuilder.add("schemas", arrayBuilder);
        Context parentContext = Contexts.context().orElseGet(Contexts::globalContext);
        Context childContext = Context.builder().parent(parentContext).build();
        tracing.findParent().ifPresent(childContext::register);
        WebClientRequestBuilder post = oidcConfig().generalWebClient().post().context(childContext).uri(multitenantEndpoints.assertEndpoint(idcsTenantId)).headers(it -> {
            it.add(Http.Header.AUTHORIZATION, "Bearer " + appToken);
            return it;
        });
        return processRoleRequest(post, requestBuilder.build(), subjectName);
    });
}
Also used : ProviderRequest(io.helidon.security.ProviderRequest) WebClient(io.helidon.webclient.WebClient) Context(io.helidon.common.context.Context) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) SecurityException(io.helidon.security.SecurityException) OidcConfig(io.helidon.security.providers.oidc.common.OidcConfig) EvictableCache(io.helidon.security.providers.common.EvictableCache) Single(io.helidon.common.reactive.Single) Grant(io.helidon.security.Grant) Subject(io.helidon.security.Subject) URI(java.net.URI) LinkedList(java.util.LinkedList) Http(io.helidon.common.http.Http) SecurityTracing(io.helidon.security.integration.common.SecurityTracing) Config(io.helidon.config.Config) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SecurityProvider(io.helidon.security.spi.SecurityProvider) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) TokenHandler(io.helidon.security.util.TokenHandler) Logger(java.util.logging.Logger) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Contexts(io.helidon.common.context.Contexts) Json(jakarta.json.Json) Objects(java.util.Objects) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) List(java.util.List) Optional(java.util.Optional) RoleMapTracing(io.helidon.security.integration.common.RoleMapTracing) Collections(java.util.Collections) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) Context(io.helidon.common.context.Context) RoleMapTracing(io.helidon.security.integration.common.RoleMapTracing) SecurityException(io.helidon.security.SecurityException) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) Contexts(io.helidon.common.context.Contexts) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder)

Example 2 with SecurityException

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

the class DbService method getNoContext.

/**
 * Get the TODO identified by the given ID from the database, fails if the
 * entry is not associated with the given {@code userId}.
 * @param id the ID identifying the entry to retrieve
 * @param userId the database user id
 * @return retrieved entry as {@code Optional}
 */
private Optional<Todo> getNoContext(final String id, final String userId) {
    BoundStatement bs = getStatement.bind(id);
    ResultSet rs = session.execute(bs);
    Row one = rs.one();
    if (null == one) {
        return Optional.empty();
    }
    Todo result = Todo.fromDb(one);
    if (userId.equals(result.getUserId())) {
        return Optional.of(result);
    }
    throw new SecurityException("User " + userId + " attempted to read record " + id + " of another user");
}
Also used : ResultSet(com.datastax.driver.core.ResultSet) SecurityException(io.helidon.security.SecurityException) Row(com.datastax.driver.core.Row) BoundStatement(com.datastax.driver.core.BoundStatement)

Example 3 with SecurityException

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

the class IdcsRoleMapperRxProvider method getGrantsFromServer.

/**
 * Retrieves grants from IDCS server.
 *
 * @param subject to get grants for
 * @return optional list of grants to be added
 */
protected Single<List<? extends Grant>> getGrantsFromServer(Subject subject) {
    String subjectName = subject.principal().getName();
    String subjectType = (String) subject.principal().abacAttribute("sub_type").orElse(defaultIdcsSubjectType());
    RoleMapTracing tracing = SecurityTracing.get().roleMapTracing("idcs");
    return Single.create(appToken.getToken(tracing)).flatMapSingle(maybeAppToken -> {
        if (maybeAppToken.isEmpty()) {
            return Single.error(new SecurityException("Application token not available"));
        }
        String appToken = maybeAppToken.get();
        JsonObjectBuilder requestBuilder = JSON.createObjectBuilder().add("mappingAttributeValue", subjectName).add("subjectType", subjectType).add("includeMemberships", true);
        JsonArrayBuilder arrayBuilder = JSON.createArrayBuilder();
        arrayBuilder.add("urn:ietf:params:scim:schemas:oracle:idcs:Asserter");
        requestBuilder.add("schemas", arrayBuilder);
        // use current span context as a parent for client outbound
        // using a custom child context, so we do not replace the parent in the current context
        Context parentContext = Contexts.context().orElseGet(Contexts::globalContext);
        Context childContext = Context.builder().parent(parentContext).build();
        tracing.findParent().ifPresent(childContext::register);
        WebClientRequestBuilder request = oidcConfig().generalWebClient().post().uri(asserterUri).context(childContext).headers(it -> {
            it.add(Http.Header.AUTHORIZATION, "Bearer " + appToken);
            return it;
        });
        return processRoleRequest(request, requestBuilder.build(), subjectName);
    }).peek(ignored -> tracing.finish()).onError(tracing::error);
}
Also used : Context(io.helidon.common.context.Context) ProviderRequest(io.helidon.security.ProviderRequest) Context(io.helidon.common.context.Context) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) SecurityException(io.helidon.security.SecurityException) OidcConfig(io.helidon.security.providers.oidc.common.OidcConfig) EvictableCache(io.helidon.security.providers.common.EvictableCache) Single(io.helidon.common.reactive.Single) Grant(io.helidon.security.Grant) Subject(io.helidon.security.Subject) URI(java.net.URI) LinkedList(java.util.LinkedList) Http(io.helidon.common.http.Http) SecurityTracing(io.helidon.security.integration.common.SecurityTracing) Config(io.helidon.config.Config) SubjectMappingProvider(io.helidon.security.spi.SubjectMappingProvider) SecurityProvider(io.helidon.security.spi.SecurityProvider) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Contexts(io.helidon.common.context.Contexts) Json(jakarta.json.Json) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) List(java.util.List) Optional(java.util.Optional) RoleMapTracing(io.helidon.security.integration.common.RoleMapTracing) Collections(java.util.Collections) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) RoleMapTracing(io.helidon.security.integration.common.RoleMapTracing) SecurityException(io.helidon.security.SecurityException) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) Contexts(io.helidon.common.context.Contexts) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder)

Example 4 with SecurityException

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

the class IdcsSupport method signJwk.

// load signature jwk with a token, blocking operation
static JwkKeys signJwk(WebClient appWebClient, WebClient generalClient, URI tokenEndpointUri, URI signJwkUri, Duration clientTimeout) {
    // need to get token to be able to request this endpoint
    FormParams form = FormParams.builder().add("grant_type", "client_credentials").add("scope", "urn:opc:idm:__myscopes__").build();
    try {
        WebClientResponse response = appWebClient.post().uri(tokenEndpointUri).accept(MediaType.APPLICATION_JSON).submit(form).await(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
        if (response.status().family() == Http.ResponseStatus.Family.SUCCESSFUL) {
            JsonObject json = response.content().as(JsonObject.class).await(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
            String accessToken = json.getString("access_token");
            // get the jwk from server
            JsonObject jwkJson = generalClient.get().uri(signJwkUri).headers(it -> {
                it.add(Http.Header.AUTHORIZATION, "Bearer " + accessToken);
                return it;
            }).request(JsonObject.class).await(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
            return JwkKeys.create(jwkJson);
        } else {
            String errorEntity = response.content().as(String.class).await(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
            throw new SecurityException("Failed to read JWK from IDCS. Status: " + response.status() + ", entity: " + errorEntity);
        }
    } catch (SecurityException e) {
        throw e;
    } catch (Exception e) {
        throw new SecurityException("Failed to read JWK from IDCS", e);
    }
}
Also used : WebClientResponse(io.helidon.webclient.WebClientResponse) FormParams(io.helidon.common.http.FormParams) JsonObject(jakarta.json.JsonObject) SecurityException(io.helidon.security.SecurityException) SecurityException(io.helidon.security.SecurityException)

Example 5 with SecurityException

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

the class OciOutboundSecurityProvider method sign.

private OutboundSecurityResponse sign(SecurityEnvironment outboundEnv, OutboundTarget target) {
    SignatureTarget signatureTarget = target.customObject(SignatureTarget.class).orElseThrow(() -> new SecurityException("Failed to find signature configuration for target " + target.name()));
    Map<String, List<String>> newHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    newHeaders.putAll(outboundEnv.headers());
    OciSignatureData sigData = signatureData.get();
    LOGGER.finest("Creating request signature with kid: " + sigData.keyId());
    OciHttpSignature signature = OciHttpSignature.sign(SignatureRequest.builder().env(outboundEnv).privateKey(sigData.privateKey()).keyId(sigData.keyId()).headersConfig(signatureTarget.signedHeadersConfig).newHeaders(newHeaders).build());
    TOKEN_HANDLER.addHeader(newHeaders, signature.toSignatureHeader());
    return OutboundSecurityResponse.builder().requestHeaders(newHeaders).status(SecurityResponse.SecurityStatus.SUCCESS).build();
}
Also used : SecurityException(io.helidon.security.SecurityException) List(java.util.List) TreeMap(java.util.TreeMap)

Aggregations

SecurityException (io.helidon.security.SecurityException)5 List (java.util.List)3 Context (io.helidon.common.context.Context)2 Contexts (io.helidon.common.context.Contexts)2 Http (io.helidon.common.http.Http)2 Single (io.helidon.common.reactive.Single)2 Config (io.helidon.config.Config)2 AuthenticationResponse (io.helidon.security.AuthenticationResponse)2 Grant (io.helidon.security.Grant)2 ProviderRequest (io.helidon.security.ProviderRequest)2 Subject (io.helidon.security.Subject)2 RoleMapTracing (io.helidon.security.integration.common.RoleMapTracing)2 SecurityTracing (io.helidon.security.integration.common.SecurityTracing)2 EvictableCache (io.helidon.security.providers.common.EvictableCache)2 OidcConfig (io.helidon.security.providers.oidc.common.OidcConfig)2 SecurityProvider (io.helidon.security.spi.SecurityProvider)2 WebClientRequestBuilder (io.helidon.webclient.WebClientRequestBuilder)2 Json (jakarta.json.Json)2 JsonArrayBuilder (jakarta.json.JsonArrayBuilder)2 JsonBuilderFactory (jakarta.json.JsonBuilderFactory)2