Search in sources :

Example 21 with Subject

use of io.helidon.security.Subject 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 22 with Subject

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

the class HeaderAtnProviderTest method testServiceExtraction.

@Test
public void testServiceExtraction() {
    HeaderAtnProvider provider = getServiceProvider();
    String username = "service";
    SecurityEnvironment env = SecurityEnvironment.builder().header("Authorization", "bearer " + username).build();
    ProviderRequest request = mock(ProviderRequest.class);
    when(request.env()).thenReturn(env);
    AuthenticationResponse response = provider.syncAuthenticate(request);
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.SUCCESS));
    assertThat(response.user(), is(Optional.empty()));
    assertThat(response.service(), is(not(Optional.empty())));
    response.service().map(Subject::principal).map(Principal::getName).ifPresent(name -> assertThat(name, is(username)));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Subject(io.helidon.security.Subject) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Example 23 with Subject

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

the class OidcProvider method buildSubject.

private Subject buildSubject(Jwt jwt, SignedJwt signedJwt) {
    Principal principal = buildPrincipal(jwt);
    TokenCredential.Builder builder = TokenCredential.builder();
    jwt.issueTime().ifPresent(builder::issueTime);
    jwt.expirationTime().ifPresent(builder::expTime);
    jwt.issuer().ifPresent(builder::issuer);
    builder.token(signedJwt.tokenContent());
    builder.addToken(Jwt.class, jwt);
    builder.addToken(SignedJwt.class, signedJwt);
    Subject.Builder subjectBuilder = Subject.builder().principal(principal).addPublicCredential(TokenCredential.class, builder.build());
    if (useJwtGroups) {
        Optional<List<String>> userGroups = jwt.userGroups();
        userGroups.ifPresent(groups -> groups.forEach(group -> subjectBuilder.addGrant(Role.create(group))));
    }
    Optional<List<String>> scopes = jwt.scopes();
    scopes.ifPresent(scopeList -> scopeList.forEach(scope -> subjectBuilder.addGrant(Grant.builder().name(scope).type("scope").build())));
    return subjectBuilder.build();
}
Also used : Arrays(java.util.Arrays) Security(io.helidon.security.Security) JwtException(io.helidon.security.jwt.JwtException) BiFunction(java.util.function.BiFunction) DeprecatedConfig(io.helidon.config.DeprecatedConfig) MediaType(io.helidon.common.http.MediaType) ScopeValidator(io.helidon.security.abac.scope.ScopeValidator) Matcher(java.util.regex.Matcher) Map(java.util.Map) FormParams(io.helidon.common.http.FormParams) Grant(io.helidon.security.Grant) ConfiguredOption(io.helidon.config.metadata.ConfiguredOption) SecurityLevel(io.helidon.security.SecurityLevel) JwtUtil(io.helidon.security.jwt.JwtUtil) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) Logger(java.util.logging.Logger) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Role(io.helidon.security.Role) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Errors(io.helidon.common.Errors) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) ProviderRequest(io.helidon.security.ProviderRequest) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Level(java.util.logging.Level) HashSet(java.util.HashSet) SignedJwt(io.helidon.security.jwt.SignedJwt) OidcCookieHandler(io.helidon.security.providers.oidc.common.OidcCookieHandler) AuthenticationProvider(io.helidon.security.spi.AuthenticationProvider) OidcConfig(io.helidon.security.providers.oidc.common.OidcConfig) BiConsumer(java.util.function.BiConsumer) Single(io.helidon.common.reactive.Single) Subject(io.helidon.security.Subject) TokenCredential(io.helidon.security.providers.common.TokenCredential) LinkedList(java.util.LinkedList) Http(io.helidon.common.http.Http) Config(io.helidon.config.Config) OutboundSecurityProvider(io.helidon.security.spi.OutboundSecurityProvider) Configured(io.helidon.config.metadata.Configured) SecurityProvider(io.helidon.security.spi.SecurityProvider) OidcConfig.postJsonResponse(io.helidon.security.providers.oidc.common.OidcConfig.postJsonResponse) TokenHandler(io.helidon.security.util.TokenHandler) OutboundConfig(io.helidon.security.providers.common.OutboundConfig) Principal(io.helidon.security.Principal) JwkKeys(io.helidon.security.jwt.jwk.JwkKeys) SecurityResponse(io.helidon.security.SecurityResponse) URLEncoder(java.net.URLEncoder) EndpointConfig(io.helidon.security.EndpointConfig) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Jwt(io.helidon.security.jwt.Jwt) OutboundTarget(io.helidon.security.providers.common.OutboundTarget) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) List(java.util.List) LinkedList(java.util.LinkedList) TokenCredential(io.helidon.security.providers.common.TokenCredential) Principal(io.helidon.security.Principal) Subject(io.helidon.security.Subject)

Example 24 with Subject

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

the class OidcProvider method outboundSecurity.

@Override
public CompletionStage<OutboundSecurityResponse> outboundSecurity(ProviderRequest providerRequest, SecurityEnvironment outboundEnv, EndpointConfig outboundEndpointConfig) {
    Optional<Subject> user = providerRequest.securityContext().user();
    if (user.isPresent()) {
        // we do have a user, let's see if we can propagate
        Subject subject = user.get();
        Optional<TokenCredential> tokenCredential = subject.publicCredential(TokenCredential.class);
        if (tokenCredential.isPresent()) {
            String tokenContent = tokenCredential.get().token();
            OidcOutboundTarget target = outboundConfig.findTarget(outboundEnv);
            boolean enabled = target.propagate;
            if (enabled) {
                Map<String, List<String>> headers = new HashMap<>(outboundEnv.headers());
                target.tokenHandler.header(headers, tokenContent);
                return CompletableFuture.completedFuture(OutboundSecurityResponse.withHeaders(headers));
            }
        }
    }
    return CompletableFuture.completedFuture(OutboundSecurityResponse.empty());
}
Also used : HashMap(java.util.HashMap) List(java.util.List) LinkedList(java.util.LinkedList) TokenCredential(io.helidon.security.providers.common.TokenCredential) Subject(io.helidon.security.Subject)

Example 25 with Subject

use of io.helidon.security.Subject 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)

Aggregations

Subject (io.helidon.security.Subject)36 ProviderRequest (io.helidon.security.ProviderRequest)22 SecurityContext (io.helidon.security.SecurityContext)18 SecurityEnvironment (io.helidon.security.SecurityEnvironment)18 AuthenticationResponse (io.helidon.security.AuthenticationResponse)17 Test (org.junit.jupiter.api.Test)17 Principal (io.helidon.security.Principal)16 EndpointConfig (io.helidon.security.EndpointConfig)15 OutboundSecurityResponse (io.helidon.security.OutboundSecurityResponse)15 SignedJwt (io.helidon.security.jwt.SignedJwt)11 Config (io.helidon.config.Config)10 Jwt (io.helidon.security.jwt.Jwt)9 Optional (java.util.Optional)8 Instant (java.time.Instant)7 Locale (java.util.Locale)7 TokenCredential (io.helidon.security.providers.common.TokenCredential)6 LinkedList (java.util.LinkedList)6 List (java.util.List)6 Errors (io.helidon.common.Errors)4 MediaType (io.helidon.common.http.MediaType)4