Search in sources :

Example 1 with SecurityIdentity

use of io.quarkus.security.identity.SecurityIdentity in project quarkus by quarkusio.

the class SecurityContextOverrideHandler method updateIdentity.

private void updateIdentity(ResteasyReactiveRequestContext requestContext, SecurityContext modified) {
    requestContext.requireCDIRequestScope();
    InjectableInstance<CurrentIdentityAssociation> instance = getCurrentIdentityAssociation();
    if (instance.isResolvable()) {
        CurrentIdentityAssociation currentIdentityAssociation = instance.get();
        Uni<SecurityIdentity> oldIdentity = currentIdentityAssociation.getDeferredIdentity();
        currentIdentityAssociation.setIdentity(oldIdentity.map(new Function<SecurityIdentity, SecurityIdentity>() {

            @Override
            public SecurityIdentity apply(SecurityIdentity old) {
                Set<Credential> oldCredentials = old.getCredentials();
                Map<String, Object> oldAttributes = old.getAttributes();
                return new SecurityIdentity() {

                    @Override
                    public Principal getPrincipal() {
                        return modified.getUserPrincipal();
                    }

                    @Override
                    public boolean isAnonymous() {
                        return modified.getUserPrincipal() == null;
                    }

                    @Override
                    public Set<String> getRoles() {
                        throw new UnsupportedOperationException("retrieving all roles not supported when JAX-RS security context has been replaced");
                    }

                    @Override
                    public boolean hasRole(String role) {
                        return modified.isUserInRole(role);
                    }

                    @SuppressWarnings("unchecked")
                    @Override
                    public <T extends Credential> T getCredential(Class<T> credentialType) {
                        for (Credential cred : getCredentials()) {
                            if (credentialType.isAssignableFrom(cred.getClass())) {
                                return (T) cred;
                            }
                        }
                        return null;
                    }

                    @Override
                    public Set<Credential> getCredentials() {
                        return oldCredentials;
                    }

                    @SuppressWarnings("unchecked")
                    @Override
                    public <T> T getAttribute(String name) {
                        return (T) oldAttributes.get(name);
                    }

                    @Override
                    public Map<String, Object> getAttributes() {
                        return oldAttributes;
                    }

                    @Override
                    public Uni<Boolean> checkPermission(Permission permission) {
                        return Uni.createFrom().nullItem();
                    }
                };
            }
        }));
    }
}
Also used : Credential(io.quarkus.security.credential.Credential) SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) Function(java.util.function.Function) CurrentIdentityAssociation(io.quarkus.security.identity.CurrentIdentityAssociation) Permission(java.security.Permission) ResourceClass(org.jboss.resteasy.reactive.common.model.ResourceClass)

Example 2 with SecurityIdentity

use of io.quarkus.security.identity.SecurityIdentity in project quarkus by quarkusio.

the class WebAuthnController method callback.

/**
 * Endpoint for callback
 *
 * @param ctx the current request
 */
public void callback(RoutingContext ctx) {
    try {
        // might throw runtime exception if there's no json or is bad formed
        final JsonObject webauthnResp = ctx.getBodyAsJson();
        // input validation
        if (webauthnResp == null || !containsRequiredString(webauthnResp, "id") || !containsRequiredString(webauthnResp, "rawId") || !containsRequiredObject(webauthnResp, "response") || !containsOptionalString(webauthnResp.getJsonObject("response"), "userHandle") || !containsRequiredString(webauthnResp, "type") || !"public-key".equals(webauthnResp.getString("type"))) {
            ctx.fail(400, new IllegalArgumentException("Response missing one or more of id/rawId/response[.userHandle]/type fields, or type is not public-key"));
            return;
        }
        RestoreResult challenge = authMech.getLoginManager().restore(ctx, CHALLENGE_COOKIE);
        RestoreResult username = authMech.getLoginManager().restore(ctx, USERNAME_COOKIE);
        if (challenge == null || challenge.getPrincipal() == null || challenge.getPrincipal().isEmpty() || username == null || username.getPrincipal() == null || username.getPrincipal().isEmpty()) {
            ctx.fail(400, new IllegalArgumentException("Missing challenge or username"));
            return;
        }
        ManagedContext requestContext = Arc.container().requestContext();
        requestContext.activate();
        ContextState contextState = requestContext.getState();
        // input basic validation is OK
        // authInfo
        WebAuthnCredentials credentials = new WebAuthnCredentials().setOrigin(origin).setDomain(domain).setChallenge(challenge.getPrincipal()).setUsername(username.getPrincipal()).setWebauthn(webauthnResp);
        identityProviderManager.authenticate(HttpSecurityUtils.setRoutingContextAttribute(new WebAuthnAuthenticationRequest(credentials), ctx)).subscribe().with(new Consumer<SecurityIdentity>() {

            @Override
            public void accept(SecurityIdentity identity) {
                requestContext.destroy(contextState);
                // invalidate the challenge
                WebAuthnSecurity.removeCookie(ctx, WebAuthnController.CHALLENGE_COOKIE);
                WebAuthnSecurity.removeCookie(ctx, WebAuthnController.USERNAME_COOKIE);
                try {
                    authMech.getLoginManager().save(identity, ctx, null, ctx.request().isSSL());
                    ok(ctx);
                } catch (Throwable t) {
                    log.error("Unable to complete post authentication", t);
                    ctx.fail(t);
                }
            }
        }, new Consumer<Throwable>() {

            @Override
            public void accept(Throwable throwable) {
                requestContext.terminate();
                if (throwable instanceof AttestationException) {
                    ctx.fail(400, throwable);
                } else {
                    ctx.fail(throwable);
                }
            }
        });
    } catch (IllegalArgumentException e) {
        ctx.fail(400, e);
    } catch (RuntimeException e) {
        ctx.fail(e);
    }
}
Also used : AttestationException(io.vertx.ext.auth.webauthn.impl.attestation.AttestationException) RestoreResult(io.quarkus.vertx.http.runtime.security.PersistentLoginManager.RestoreResult) JsonObject(io.vertx.core.json.JsonObject) SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) WebAuthnCredentials(io.vertx.ext.auth.webauthn.WebAuthnCredentials) ContextState(io.quarkus.arc.InjectableContext.ContextState) ManagedContext(io.quarkus.arc.ManagedContext)

Example 3 with SecurityIdentity

use of io.quarkus.security.identity.SecurityIdentity in project quarkus by quarkusio.

the class QuarkusIdentityProviderManagerImpl method handleProvider.

private <T extends AuthenticationRequest> Uni<SecurityIdentity> handleProvider(int pos, List<IdentityProvider<T>> providers, T request, AuthenticationRequestContext context) {
    if (pos == providers.size()) {
        // we failed to authentication
        log.debug("Authentication failed as providers would authenticate the request");
        return Uni.createFrom().failure(new AuthenticationFailedException());
    }
    IdentityProvider<T> current = providers.get(pos);
    Uni<SecurityIdentity> cs = current.authenticate(request, context).onItem().transformToUni(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() {

        @Override
        public Uni<SecurityIdentity> apply(SecurityIdentity securityIdentity) {
            if (securityIdentity != null) {
                return Uni.createFrom().item(securityIdentity);
            }
            return handleProvider(pos + 1, providers, request, context);
        }
    });
    return cs.onItem().transformToUni(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() {

        @Override
        public Uni<? extends SecurityIdentity> apply(SecurityIdentity securityIdentity) {
            return handleIdentityFromProvider(0, securityIdentity, context);
        }
    });
}
Also used : SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) Uni(io.smallrye.mutiny.Uni) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException)

Example 4 with SecurityIdentity

use of io.quarkus.security.identity.SecurityIdentity in project quarkus by quarkusio.

the class QuarkusSecurityIdentityTest method testPrincipalNullAnonymousFalseWithCustomIdentityFixed.

@Test
public void testPrincipalNullAnonymousFalseWithCustomIdentityFixed() throws Exception {
    SecurityIdentity identity1 = new TestSecurityIdentityPrincipalNullAnonymousFalse();
    assertFalse(identity1.isAnonymous());
    assertNull(identity1.getPrincipal());
    SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).setAnonymous(true).build();
    assertTrue(identity2.isAnonymous());
    assertNull(identity2.getPrincipal());
}
Also used : SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) Test(org.junit.jupiter.api.Test)

Example 5 with SecurityIdentity

use of io.quarkus.security.identity.SecurityIdentity in project quarkus by quarkusio.

the class UndertowDeploymentRecorder method setupRequestScope.

public void setupRequestScope(DeploymentInfo deploymentInfo, BeanContainer beanContainer) {
    CurrentVertxRequest currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get();
    Instance<CurrentIdentityAssociation> identityAssociations = CDI.current().select(CurrentIdentityAssociation.class);
    CurrentIdentityAssociation association;
    if (identityAssociations.isResolvable()) {
        association = identityAssociations.get();
    } else {
        association = null;
    }
    deploymentInfo.addThreadSetupAction(new ThreadSetupHandler() {

        @Override
        public <T, C> ThreadSetupHandler.Action<T, C> create(Action<T, C> action) {
            return new Action<T, C>() {

                @Override
                public T call(HttpServerExchange exchange, C context) throws Exception {
                    // Not sure what to do here
                    ManagedContext requestContext = beanContainer.requestContext();
                    if (requestContext.isActive()) {
                        return action.call(exchange, context);
                    } else if (exchange == null) {
                        requestContext.activate();
                        try {
                            return action.call(exchange, context);
                        } finally {
                            requestContext.terminate();
                        }
                    } else {
                        InjectableContext.ContextState existingRequestContext = exchange.getAttachment(REQUEST_CONTEXT);
                        try {
                            requestContext.activate(existingRequestContext);
                            VertxHttpExchange delegate = (VertxHttpExchange) exchange.getDelegate();
                            RoutingContext rc = (RoutingContext) delegate.getContext();
                            currentVertxRequest.setCurrent(rc);
                            if (association != null) {
                                QuarkusHttpUser existing = (QuarkusHttpUser) rc.user();
                                if (existing != null) {
                                    SecurityIdentity identity = existing.getSecurityIdentity();
                                    association.setIdentity(identity);
                                } else {
                                    association.setIdentity(QuarkusHttpUser.getSecurityIdentity(rc, null));
                                }
                            }
                            return action.call(exchange, context);
                        } finally {
                            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                            HttpServletRequestImpl req = src.getOriginalRequest();
                            if (req.isAsyncStarted()) {
                                exchange.putAttachment(REQUEST_CONTEXT, requestContext.getState());
                                requestContext.deactivate();
                                if (existingRequestContext == null) {
                                    req.getAsyncContextInternal().addListener(new AsyncListener() {

                                        @Override
                                        public void onComplete(AsyncEvent event) throws IOException {
                                            requestContext.activate(exchange.getAttachment(REQUEST_CONTEXT));
                                            requestContext.terminate();
                                        }

                                        @Override
                                        public void onTimeout(AsyncEvent event) throws IOException {
                                            onComplete(event);
                                        }

                                        @Override
                                        public void onError(AsyncEvent event) throws IOException {
                                            onComplete(event);
                                        }

                                        @Override
                                        public void onStartAsync(AsyncEvent event) throws IOException {
                                        }
                                    });
                                }
                            } else {
                                requestContext.terminate();
                            }
                        }
                    }
                }
            };
        }
    });
}
Also used : InjectableContext(io.quarkus.arc.InjectableContext) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) IOException(java.io.IOException) CurrentVertxRequest(io.quarkus.vertx.http.runtime.CurrentVertxRequest) AsyncEvent(javax.servlet.AsyncEvent) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) ForbiddenException(io.quarkus.security.ForbiddenException) UnauthorizedException(io.quarkus.security.UnauthorizedException) HttpServerExchange(io.undertow.server.HttpServerExchange) SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) VertxHttpExchange(io.undertow.vertx.VertxHttpExchange) RoutingContext(io.vertx.ext.web.RoutingContext) HttpServletRequestImpl(io.undertow.servlet.spec.HttpServletRequestImpl) CurrentIdentityAssociation(io.quarkus.security.identity.CurrentIdentityAssociation) AsyncListener(javax.servlet.AsyncListener) ManagedContext(io.quarkus.arc.ManagedContext) QuarkusHttpUser(io.quarkus.vertx.http.runtime.security.QuarkusHttpUser)

Aggregations

SecurityIdentity (io.quarkus.security.identity.SecurityIdentity)42 QuarkusHttpUser (io.quarkus.vertx.http.runtime.security.QuarkusHttpUser)11 Uni (io.smallrye.mutiny.Uni)9 AuthenticationFailedException (io.quarkus.security.AuthenticationFailedException)8 Test (org.junit.jupiter.api.Test)8 QuarkusSecurityIdentity (io.quarkus.security.runtime.QuarkusSecurityIdentity)7 ManagedContext (io.quarkus.arc.ManagedContext)6 IdTokenCredential (io.quarkus.oidc.IdTokenCredential)5 Principal (java.security.Principal)5 AccessTokenCredential (io.quarkus.oidc.AccessTokenCredential)4 RoutingContext (io.vertx.ext.web.RoutingContext)4 AuthenticationCompletionException (io.quarkus.security.AuthenticationCompletionException)3 AuthenticationRedirectException (io.quarkus.security.AuthenticationRedirectException)3 TokenAuthenticationRequest (io.quarkus.security.identity.request.TokenAuthenticationRequest)3 Function (java.util.function.Function)3 ContextState (io.quarkus.arc.InjectableContext.ContextState)2 AuthorizationCodeTokens (io.quarkus.oidc.AuthorizationCodeTokens)2 Credential (io.quarkus.security.credential.Credential)2 TokenCredential (io.quarkus.security.credential.TokenCredential)2 AuthenticationRequestContext (io.quarkus.security.identity.AuthenticationRequestContext)2