Search in sources :

Example 21 with AuthenticationContext

use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.

the class AnnSBTest method testSingleMethodAnnotationsUser1Template.

/**
 * Test objective:
 * Check if default, @RolesAllowed, @PermitAll, @DenyAll and @RolesAllowed with multiple roles
 * works on method level with user1 logged in as described in EJB 3.1 spec.
 * user1 has "Users,Role1" roles.
 * The target session bean is given as parameter.
 * Expected results:
 * Test has to finish without any exception or error.
 * <p/>
 *
 * @throws Exception
 */
public void testSingleMethodAnnotationsUser1Template(final String MODULE, final Logger log, final Class SB_CLASS) throws Exception {
    final Context ctx = Util.createNamingContext();
    final AuthenticationContext authenticationContext = setupAuthenticationContext("user1", "password1");
    authenticationContext.runCallable(() -> {
        try {
            String echoValue = getBean(MODULE, log, SB_CLASS, ctx).defaultAccess("alohomora");
            Assert.assertEquals(echoValue, "alohomora");
        } catch (EJBAccessException e) {
            Assert.fail("EJBAccessException not expected");
        }
        try {
            String echoValue = getBean(MODULE, log, SB_CLASS, ctx).roleBasedAccessOne("alohomora");
            Assert.assertEquals(echoValue, "alohomora");
        } catch (EJBAccessException e) {
            Assert.fail("EJBAccessException not expected");
        }
        try {
            String echoValue = getBean(MODULE, log, SB_CLASS, ctx).roleBasedAccessMore("alohomora");
            Assert.fail("Method cannot be successfully called with logged in principal.");
        } catch (Exception e) {
            // expected
            Assert.assertTrue("Thrown exception must be EJBAccessException, but was different", e instanceof EJBAccessException);
        }
        try {
            String echoValue = getBean(MODULE, log, SB_CLASS, ctx).permitAll("alohomora");
            Assert.assertEquals(echoValue, "alohomora");
        } catch (Exception e) {
            Assert.fail("@PermitAll annotation must allow all users and no users to call the method - principal.");
        }
        try {
            String echoValue = getBean(MODULE, log, SB_CLASS, ctx).denyAll("alohomora");
            Assert.fail("@DenyAll annotation must allow all users and no users to call the method");
        } catch (Exception e) {
            // expected
            Assert.assertTrue("Thrown exception must be EJBAccessException, but was different", e instanceof EJBAccessException);
        }
        try {
            String echoValue = getBean(MODULE, log, SB_CLASS, ctx).starRoleAllowed("alohomora");
            Assert.assertEquals(echoValue, "alohomora");
        } catch (Exception e) {
            Assert.fail("@RolesAllowed(\"**\") annotation must allow all authenticated users to the method.");
        }
        return null;
    });
}
Also used : Context(javax.naming.Context) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) EJBAccessException(javax.ejb.EJBAccessException) NamingException(javax.naming.NamingException) EJBAccessException(javax.ejb.EJBAccessException)

Example 22 with AuthenticationContext

use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.

the class AnnSBTest method testSingleMethodAnnotationsNoUserTemplate.

/**
 * Test objective:
 * Check if default, @RolesAllowed, @PermitAll, @DenyAll and @RolesAllowed with multiple roles
 * works on method level without user logged in as described in EJB 3.1 spec.
 * The target session bean is given as parameter
 * Expected results:
 * Test has to finish without any exception or error.
 *
 * @throws Exception
 */
public void testSingleMethodAnnotationsNoUserTemplate(final String MODULE, final Logger log, final Class SB_CLASS) throws Exception {
    final Context ctx = Util.createNamingContext();
    final AuthenticationContext authenticationContext = AuthenticationContext.empty().with(MatchRule.ALL, AuthenticationConfiguration.EMPTY.useAuthorizationPrincipal(AnonymousPrincipal.getInstance()));
    authenticationContext.runCallable(() -> {
        String echoValue = getBean(MODULE, log, SB_CLASS, ctx).defaultAccess("alohomora");
        Assert.assertEquals(echoValue, "alohomora");
        try {
            echoValue = getBean(MODULE, log, SB_CLASS, ctx).roleBasedAccessOne("alohomora");
            Assert.fail("Method cannot be successfully called without logged in user");
        } catch (Exception e) {
            // expected
            Assert.assertTrue("Thrown exception must be EJBAccessException, but was " + e.getClass().getSimpleName(), e instanceof EJBAccessException);
        }
        try {
            echoValue = getBean(MODULE, log, SB_CLASS, ctx).roleBasedAccessMore("alohomora");
            Assert.fail("Method cannot be successfully called without logged in user");
        } catch (EJBAccessException e) {
        // expected
        }
        try {
            echoValue = getBean(MODULE, log, SB_CLASS, ctx).permitAll("alohomora");
            Assert.assertEquals(echoValue, "alohomora");
        } catch (Exception e) {
            Assert.fail("@PermitAll annotation must allow all users and no users to call the method");
        }
        try {
            echoValue = getBean(MODULE, log, SB_CLASS, ctx).denyAll("alohomora");
            Assert.fail("@DenyAll annotation must allow all users and no users to call the method");
        } catch (Exception e) {
            // expected
            Assert.assertTrue("Thrown exception must be EJBAccessException, but was " + e.getClass().getSimpleName(), e instanceof EJBAccessException);
        }
        return null;
    });
}
Also used : Context(javax.naming.Context) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) NamingException(javax.naming.NamingException) EJBAccessException(javax.ejb.EJBAccessException) EJBAccessException(javax.ejb.EJBAccessException)

Example 23 with AuthenticationContext

use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.

the class AnnSBTest method setupAuthenticationContext.

protected AuthenticationContext setupAuthenticationContext(String username, String password) {
    OptionMap.Builder builder = OptionMap.builder().set(Options.SASL_POLICY_NOANONYMOUS, true);
    builder.set(Options.SASL_POLICY_NOPLAINTEXT, false);
    if (password != null) {
        builder.set(Options.SASL_DISALLOWED_MECHANISMS, Sequence.of("JBOSS-LOCAL-USER"));
    } else {
        builder.set(Options.SASL_MECHANISMS, Sequence.of("JBOSS-LOCAL-USER"));
    }
    final AuthenticationContext authenticationContext = AuthenticationContext.empty().with(MatchRule.ALL, AuthenticationConfiguration.EMPTY.useName(username == null ? "$local" : username).usePassword(password).useRealm(null).setSaslMechanismSelector(SaslMechanismSelector.fromString(password != null ? "DIGEST-MD5" : "JBOSS-LOCAL-USER")).useMechanismProperties(getSaslProperties(builder.getMap())).useProvidersFromClassLoader(AnnSBTest.class.getClassLoader()));
    return authenticationContext;
}
Also used : AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) OptionMap(org.xnio.OptionMap)

Example 24 with AuthenticationContext

use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.

the class ElytronSASClientInterceptor method send_request.

@Override
public void send_request(ClientRequestInfo ri) throws ForwardRequest {
    try {
        CompoundSecMech secMech = CSIv2Util.getMatchingSecurityMech(ri, codec, EstablishTrustInClient.value, /* client supports */
        (short) 0);
        if (secMech == null) {
            return;
        }
        // these "null tokens" will be changed if needed.
        IdentityToken identityToken = ABSENT_IDENTITY_TOKEN;
        byte[] encodedAuthenticationToken = NO_AUTHENTICATION_TOKEN;
        final URI uri = this.getURI(ri);
        if (uri == null) {
            return;
        }
        SecurityDomain domain = getCurrentSecurityDomain();
        SecurityIdentity currentIdentity = null;
        if (domain != null) {
            currentIdentity = domain.getCurrentSecurityIdentity();
        }
        final AuthenticationContext authContext;
        if (this.authContext != null) {
            authContext = this.authContext;
        } else if (currentIdentity == null || currentIdentity.isAnonymous()) {
            authContext = AuthenticationContext.captureCurrent();
        } else {
            authContext = AuthenticationContext.empty().with(MatchRule.ALL, AuthenticationConfiguration.empty().useForwardedIdentity(domain));
        }
        if ((secMech.sas_context_mech.target_supports & IdentityAssertion.value) != 0) {
            final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null);
            final Principal principal = AUTH_CONFIG_CLIENT.getPrincipal(configuration);
            if (principal != null && principal != AnonymousPrincipal.getInstance()) {
                // The name scope needs to be externalized.
                String name = principal.getName();
                if (name.indexOf('@') < 0) {
                    // hardcoded (REVISIT!)
                    name += "@default";
                }
                byte[] principalName = name.getBytes(StandardCharsets.UTF_8);
                // encode the principal name as mandated by RFC2743.
                byte[] encodedName = CSIv2Util.encodeGssExportedName(principalName);
                // encapsulate the encoded name.
                Any any = ORB.init().create_any();
                byte[] encapsulatedEncodedName;
                GSS_NT_ExportedNameHelper.insert(any, encodedName);
                try {
                    encapsulatedEncodedName = codec.encode_value(any);
                } catch (InvalidTypeForEncoding e) {
                    throw IIOPLogger.ROOT_LOGGER.unexpectedException(e);
                }
                // create identity token.
                identityToken = new IdentityToken();
                identityToken.principal_name(encapsulatedEncodedName);
            } else if ((secMech.sas_context_mech.supported_identity_types & ITTAnonymous.value) != 0) {
                // no run-as or caller identity and the target supports ITTAnonymous: use the anonymous identity.
                identityToken = new IdentityToken();
                identityToken.anonymous(true);
            }
            // target might require an additional initial context token with a username/password pair for authentication.
            if ((secMech.as_context_mech.target_requires & EstablishTrustInClient.value) != 0) {
                encodedAuthenticationToken = this.createInitialContextToken(uri, secMech);
            }
        } else if ((secMech.as_context_mech.target_supports & EstablishTrustInClient.value) != 0) {
            // target doesn't require an identity token but supports username/password authentication - try to build
            // an initial context token using the configuration.
            encodedAuthenticationToken = this.createInitialContextToken(uri, secMech);
        }
        if (identityToken != ABSENT_IDENTITY_TOKEN || encodedAuthenticationToken != NO_AUTHENTICATION_TOKEN) {
            // at least one non-null token was created, create EstablishContext message with it.
            EstablishContext message = new // stateless ctx id
            EstablishContext(// stateless ctx id
            0, NO_AUTHORIZATION_TOKEN, identityToken, encodedAuthenticationToken);
            // create SAS context with the EstablishContext message.
            SASContextBody contextBody = new SASContextBody();
            contextBody.establish_msg(message);
            // stuff the SAS context into the outgoing request.
            final Any any = ORB.init().create_any();
            SASContextBodyHelper.insert(any, contextBody);
            ServiceContext sc = new ServiceContext(SAS_CONTEXT_ID, codec.encode_value(any));
            ri.add_request_service_context(sc, true);
        }
    } catch (Exception e) {
        throw IIOPLogger.ROOT_LOGGER.unexpectedException(e);
    }
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) CompoundSecMech(org.omg.CSIIOP.CompoundSecMech) ServiceContext(org.omg.IOP.ServiceContext) SASContextBody(org.omg.CSI.SASContextBody) URI(java.net.URI) Any(org.omg.CORBA.Any) InvalidTypeForEncoding(org.omg.IOP.CodecPackage.InvalidTypeForEncoding) URISyntaxException(java.net.URISyntaxException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) IdentityToken(org.omg.CSI.IdentityToken) EstablishContext(org.omg.CSI.EstablishContext) AnonymousPrincipal(org.wildfly.security.auth.principal.AnonymousPrincipal) Principal(java.security.Principal)

Example 25 with AuthenticationContext

use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.

the class ElytronRemoteOutboundConnectionTestCase method callIntermediateWhoAmI.

private String callIntermediateWhoAmI(boolean useRestrictedMethod) {
    AuthenticationConfiguration common = AuthenticationConfiguration.empty().useProviders(() -> new Provider[] { new WildFlyElytronProvider() }).setSaslMechanismSelector(SaslMechanismSelector.ALL);
    AuthenticationContext authCtxEmpty = AuthenticationContext.empty();
    final AuthenticationContext authCtx = authCtxEmpty.with(MatchRule.ALL, common);
    final EJBClientContext.Builder ejbClientBuilder = new EJBClientContext.Builder();
    ejbClientBuilder.addTransportProvider(new RemoteTransportProvider());
    final EJBClientConnection.Builder connBuilder = new EJBClientConnection.Builder();
    connBuilder.setDestination(URI.create("remote+http://" + TestSuiteEnvironment.getServerAddressNode1() + ":8180"));
    ejbClientBuilder.addClientConnection(connBuilder.build());
    final EJBClientContext ejbCtx = ejbClientBuilder.build();
    AuthenticationContext.getContextManager().setThreadDefault(authCtx);
    EJBClientContext.getContextManager().setThreadDefault(ejbCtx);
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
    String result;
    try {
        InitialContext ctx = new InitialContext(props);
        String lookupName = "ejb:/outbound-module/IntermediateWhoAmI!org.jboss.as.test.manualmode.ejb.client.outbound.connection.security.WhoAmI";
        WhoAmI intermediate = (WhoAmI) ctx.lookup(lookupName);
        if (useRestrictedMethod) {
            result = intermediate.whoAmIRestricted();
        } else {
            result = intermediate.whoAmI();
        }
        ctx.close();
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    return result;
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) WildFlyInitialContextFactory(org.wildfly.naming.client.WildFlyInitialContextFactory) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) OperationBuilder(org.jboss.as.controller.client.OperationBuilder) EJBClientContext(org.jboss.ejb.client.EJBClientContext) Properties(java.util.Properties) WildFlyElytronProvider(org.wildfly.security.WildFlyElytronProvider) InitialContext(org.jboss.as.naming.InitialContext) WildFlyElytronProvider(org.wildfly.security.WildFlyElytronProvider) Provider(java.security.Provider) RemoteTransportProvider(org.jboss.ejb.protocol.remote.RemoteTransportProvider) EJBClientConnection(org.jboss.ejb.client.EJBClientConnection) NamingException(javax.naming.NamingException) RemoteTransportProvider(org.jboss.ejb.protocol.remote.RemoteTransportProvider)

Aggregations

AuthenticationContext (org.wildfly.security.auth.client.AuthenticationContext)48 AuthenticationConfiguration (org.wildfly.security.auth.client.AuthenticationConfiguration)28 Client (javax.ws.rs.client.Client)24 ClientBuilder (javax.ws.rs.client.ClientBuilder)24 RunAsClient (org.jboss.arquillian.container.test.api.RunAsClient)24 Test (org.junit.Test)24 Response (javax.ws.rs.core.Response)21 URL (java.net.URL)19 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)11 InvalidAuthenticationConfigurationException (org.wildfly.security.auth.client.InvalidAuthenticationConfigurationException)11 HttpClient (org.apache.http.client.HttpClient)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 BeforeClass (org.junit.BeforeClass)6 AuthenticationContextConfigurationClient (org.wildfly.security.auth.client.AuthenticationContextConfigurationClient)6 BearerTokenCredential (org.wildfly.security.credential.BearerTokenCredential)5 IOException (java.io.IOException)4 URISyntaxException (java.net.URISyntaxException)4 NamingException (javax.naming.NamingException)4 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)4 OptionMap (org.xnio.OptionMap)4