Search in sources :

Example 41 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class AssociationImpl method invokeMethod.

static Object invokeMethod(final ComponentView componentView, final Method method, final InvocationRequest incomingInvocation, final InvocationRequest.Resolved content, final CancellationFlag cancellationFlag) throws Exception {
    final InterceptorContext interceptorContext = new InterceptorContext();
    interceptorContext.setParameters(content.getParameters());
    interceptorContext.setMethod(method);
    interceptorContext.putPrivateData(Component.class, componentView.getComponent());
    interceptorContext.putPrivateData(ComponentView.class, componentView);
    interceptorContext.putPrivateData(InvocationType.class, InvocationType.REMOTE);
    interceptorContext.setBlockingCaller(false);
    // setup the contextData on the (spec specified) InvocationContext
    final Map<String, Object> invocationContextData = new HashMap<String, Object>();
    interceptorContext.setContextData(invocationContextData);
    if (content.getAttachments() != null) {
        // attach the attachments which were passed from the remote client
        for (final Map.Entry<String, Object> attachment : content.getAttachments().entrySet()) {
            if (attachment == null) {
                continue;
            }
            final String key = attachment.getKey();
            final Object value = attachment.getValue();
            // application, so add these attachments to the privateData of the InterceptorContext
            if (EJBClientInvocationContext.PRIVATE_ATTACHMENTS_KEY.equals(key)) {
                final Map<?, ?> privateAttachments = (Map<?, ?>) value;
                for (final Map.Entry<?, ?> privateAttachment : privateAttachments.entrySet()) {
                    interceptorContext.putPrivateData(privateAttachment.getKey(), privateAttachment.getValue());
                }
            } else {
                // add it to the InvocationContext which will be visible to the target bean and the
                // application specific interceptors
                invocationContextData.put(key, value);
            }
        }
    }
    // add the session id to the interceptor context, if it's a stateful ejb locator
    final EJBLocator<?> ejbLocator = content.getEJBLocator();
    if (ejbLocator.isStateful()) {
        interceptorContext.putPrivateData(SessionID.class, ejbLocator.asStateful().getSessionId());
    }
    // add transaction
    if (content.hasTransaction()) {
        interceptorContext.setTransactionSupplier(content::getTransaction);
    }
    // add security identity
    final SecurityIdentity securityIdentity = incomingInvocation.getSecurityIdentity();
    final boolean isAsync = componentView.isAsynchronous(method);
    final boolean oneWay = isAsync && method.getReturnType() == void.class;
    final boolean isSessionBean = componentView.getComponent() instanceof SessionBeanComponent;
    if (isAsync && isSessionBean) {
        if (!oneWay) {
            interceptorContext.putPrivateData(CancellationFlag.class, cancellationFlag);
        }
        final Object result = invokeWithIdentity(componentView, interceptorContext, securityIdentity);
        return result == null ? null : ((Future<?>) result).get();
    } else {
        return invokeWithIdentity(componentView, interceptorContext, securityIdentity);
    }
}
Also used : HashMap(java.util.HashMap) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) SessionBeanComponent(org.jboss.as.ejb3.component.session.SessionBeanComponent) InterceptorContext(org.jboss.invocation.InterceptorContext) Map(java.util.Map) HashMap(java.util.HashMap)

Example 42 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class ServerSecurityInterceptor method aroundInvoke.

@AroundInvoke
public Object aroundInvoke(final InvocationContext invocationContext) throws Exception {
    Principal desiredUser = null;
    RealmUser connectionUser = null;
    Map<String, Object> contextData = invocationContext.getContextData();
    if (contextData.containsKey(DELEGATED_USER_KEY)) {
        desiredUser = new SimplePrincipal((String) contextData.get(DELEGATED_USER_KEY));
        Connection con = RemotingContext.getConnection();
        if (con != null) {
            SecurityIdentity localIdentity = con.getLocalIdentity();
            if (localIdentity != null) {
                connectionUser = new RealmUser(localIdentity.getPrincipal().getName());
            }
        } else {
            throw new IllegalStateException("Delegation user requested but no user on connection found.");
        }
    }
    SecurityContext cachedSecurityContext = null;
    boolean contextSet = false;
    try {
        if (desiredUser != null && connectionUser != null && (desiredUser.getName().equals(connectionUser.getName()) == false)) {
            try {
                // The final part of this check is to verify that the change does actually indicate a change in user.
                // We have been requested to switch user and have successfully identified the user from the connection
                // so now we attempt the switch.
                cachedSecurityContext = SecurityContextAssociation.getSecurityContext();
                final SecurityContext nextContext = SecurityContextFactory.createSecurityContext(desiredUser, new CurrentUserCredential(connectionUser.getName()), new Subject(), "fooSecurityDomain");
                SecurityContextAssociation.setSecurityContext(nextContext);
                // keep track that we switched the security context
                contextSet = true;
                RemotingContext.clear();
            } catch (Exception e) {
                LOGGER.error("Failed to switch security context for user", e);
                // Don't propagate the exception stacktrace back to the client for security reasons
                throw new EJBAccessException("Unable to attempt switching of user.");
            }
        }
        return invocationContext.proceed();
    } finally {
        // switch back to original security context
        if (contextSet) {
            SecurityContextAssociation.setSecurityContext(cachedSecurityContext);
        }
    }
}
Also used : IllegalStateException(javax.resource.spi.IllegalStateException) RealmUser(org.jboss.as.core.security.RealmUser) Connection(org.jboss.remoting3.Connection) Subject(javax.security.auth.Subject) EJBAccessException(javax.ejb.EJBAccessException) IllegalStateException(javax.resource.spi.IllegalStateException) EJBAccessException(javax.ejb.EJBAccessException) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) SecurityContext(org.jboss.security.SecurityContext) Principal(java.security.Principal) SimplePrincipal(org.jboss.security.SimplePrincipal) SimplePrincipal(org.jboss.security.SimplePrincipal) AroundInvoke(javax.interceptor.AroundInvoke)

Example 43 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class JdbcTestServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    final PrintWriter writer = resp.getWriter();
    Map<String, String[]> parameters = req.getParameterMap();
    SecurityDomain securityDomain = SecurityDomain.getCurrent();
    SecurityIdentity securityIdentity = securityDomain.getCurrentSecurityIdentity();
    Attributes attributes = securityIdentity.getAttributes();
    for (Entry<String, String[]> entry : parameters.entrySet()) {
        for (String value : entry.getValue()) {
            if (attributes.containsValue(entry.getKey(), value) == false) {
                writer.write(String.format("Attribute %s with value %s missing from the Attributes associated with the current SecurityIdentity.", entry.getKey(), value));
                writer.close();
                return;
            }
        }
    }
    writer.write(RESPONSE_BODY);
    writer.close();
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) Attributes(org.wildfly.security.authz.Attributes) PrintWriter(java.io.PrintWriter) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain)

Example 44 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class HttpInvokerHostService method secureAccess.

private static HttpHandler secureAccess(HttpHandler domainHandler, final HttpAuthenticationFactory httpAuthenticationFactory) {
    domainHandler = new AuthenticationCallHandler(domainHandler);
    domainHandler = new AuthenticationConstraintHandler(domainHandler);
    Supplier<List<HttpServerAuthenticationMechanism>> mechanismSupplier = () -> httpAuthenticationFactory.getMechanismNames().stream().map(s -> {
        try {
            return httpAuthenticationFactory.createMechanism(s);
        } catch (Exception e) {
            return null;
        }
    }).collect(Collectors.toList());
    domainHandler = ElytronContextAssociationHandler.builder().setNext(domainHandler).setMechanismSupplier(mechanismSupplier).setHttpExchangeSupplier(h -> new ElytronHttpExchange(h) {

        @Override
        public void authenticationComplete(SecurityIdentity securityIdentity, String mechanismName) {
            super.authenticationComplete(securityIdentity, mechanismName);
            h.putAttachment(ElytronIdentityHandler.IDENTITY_KEY, securityIdentity);
        }
    }).build();
    return domainHandler;
}
Also used : CookieImpl(io.undertow.server.handlers.CookieImpl) StopContext(org.jboss.msc.service.StopContext) AuthenticationConstraintHandler(io.undertow.security.handlers.AuthenticationConstraintHandler) StartContext(org.jboss.msc.service.StartContext) SecureRandomSessionIdGenerator(io.undertow.server.session.SecureRandomSessionIdGenerator) Service(org.jboss.msc.Service) HttpAuthenticationFactory(org.wildfly.security.auth.server.HttpAuthenticationFactory) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) Cookie(io.undertow.server.handlers.Cookie) HttpHandler(io.undertow.server.HttpHandler) SimpleRoutingSupport(org.jboss.as.web.session.SimpleRoutingSupport) List(java.util.List) PathHandler(io.undertow.server.handlers.PathHandler) ElytronContextAssociationHandler(org.wildfly.elytron.web.undertow.server.ElytronContextAssociationHandler) ElytronIdentityHandler(org.wildfly.httpclient.common.ElytronIdentityHandler) HttpServerAuthenticationMechanism(org.wildfly.security.http.HttpServerAuthenticationMechanism) SimpleSessionIdentifierCodec(org.jboss.as.web.session.SimpleSessionIdentifierCodec) AuthenticationCallHandler(io.undertow.security.handlers.AuthenticationCallHandler) ElytronHttpExchange(org.wildfly.elytron.web.undertow.server.ElytronHttpExchange) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) StatusCodes(io.undertow.util.StatusCodes) ElytronHttpExchange(org.wildfly.elytron.web.undertow.server.ElytronHttpExchange) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) AuthenticationConstraintHandler(io.undertow.security.handlers.AuthenticationConstraintHandler) AuthenticationCallHandler(io.undertow.security.handlers.AuthenticationCallHandler) List(java.util.List)

Example 45 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class BatchSubsystemSecurityTestCase method testRestart_Allowed.

/**
 * Test restarting failed jobs by a user who has the permission to do it.
 */
@Test
public void testRestart_Allowed() throws Exception {
    final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
    Properties params = new Properties();
    params.put("should.fail", "true");
    final Long executionId = user1.runAs((Callable<Long>) () -> operator.start("failing-batchlet", params));
    waitForJobEnd(executionId, 10);
    Assert.assertEquals(BatchStatus.FAILED, operator.getJobExecution(executionId).getBatchStatus());
    params.put("should.fail", "false");
    final Long executionIdAfterRestart = user1.runAs((Callable<Long>) () -> operator.restart(executionId, params));
    waitForJobEnd(executionIdAfterRestart, 10);
    Assert.assertEquals(BatchStatus.COMPLETED, operator.getJobExecution(executionIdAfterRestart).getBatchStatus());
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) Properties(java.util.Properties) Test(org.junit.Test)

Aggregations

SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)60 Test (org.junit.Test)20 Properties (java.util.Properties)16 SecurityDomain (org.wildfly.security.auth.server.SecurityDomain)15 Principal (java.security.Principal)10 JobSecurityException (javax.batch.operations.JobSecurityException)10 PrivilegedActionException (java.security.PrivilegedActionException)6 HashSet (java.util.HashSet)6 EJBComponent (org.jboss.as.ejb3.component.EJBComponent)6 Component (org.jboss.as.ee.component.Component)5 InterceptorContext (org.jboss.invocation.InterceptorContext)5 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)4 IOException (java.io.IOException)3 PrintWriter (java.io.PrintWriter)3 Method (java.lang.reflect.Method)3 PrivilegedAction (java.security.PrivilegedAction)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 SessionBeanComponent (org.jboss.as.ejb3.component.session.SessionBeanComponent)3 Connection (org.jboss.remoting3.Connection)3