Search in sources :

Example 61 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class NegotiationUtils method parseSCTResult.

/**
 * Return true on successfully parsing a SecurityContextToken result
 */
static boolean parseSCTResult(SoapMessage message) throws TokenStoreException {
    List<WSHandlerResult> results = CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
        // Try Streaming results
        @SuppressWarnings("unchecked") final List<SecurityEvent> incomingEventList = (List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in");
        if (incomingEventList != null) {
            for (SecurityEvent incomingEvent : incomingEventList) {
                if (WSSecurityEventConstants.SECURITY_CONTEXT_TOKEN == incomingEvent.getSecurityEventType()) {
                    return true;
                }
            }
        }
        return false;
    }
    for (WSHandlerResult rResult : results) {
        List<WSSecurityEngineResult> sctResults = rResult.getActionResults().get(WSConstants.SCT);
        if (sctResults != null) {
            for (WSSecurityEngineResult wser : sctResults) {
                SecurityContextToken tok = (SecurityContextToken) wser.get(WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN);
                message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getIdentifier());
                SecurityToken token = TokenStoreUtils.getTokenStore(message).getToken(tok.getIdentifier());
                if (token == null || token.isExpired()) {
                    byte[] secret = (byte[]) wser.get(WSSecurityEngineResult.TAG_SECRET);
                    if (secret != null) {
                        token = new SecurityToken(tok.getIdentifier());
                        token.setToken(tok.getElement());
                        token.setSecret(secret);
                        token.setTokenType(tok.getTokenType());
                        TokenStoreUtils.getTokenStore(message).add(token);
                    }
                }
                if (token != null) {
                    final SecurityContext sc = token.getSecurityContext();
                    if (sc != null) {
                        message.put(SecurityContext.class, sc);
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityEvent(org.apache.xml.security.stax.securityEvent.SecurityEvent) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) SecurityContext(org.apache.cxf.security.SecurityContext) List(java.util.List) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult)

Example 62 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class SamlTokenTest method testUnsignedSaml1TokenWithPrincipal.

@Test
public void testUnsignedSaml1TokenWithPrincipal() throws Exception {
    SecurityContext ctx = testSaml1Token(true);
    assertTrue(ctx.getUserPrincipal() instanceof SAMLTokenPrincipal);
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) SecurityContext(org.apache.cxf.security.SecurityContext) AbstractSecurityTest(org.apache.cxf.ws.security.wss4j.AbstractSecurityTest) Test(org.junit.Test)

Example 63 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class SamlTokenTest method testSaml1TokenWithRoles.

/**
 * This test creates a SAML1 Assertion and sends it in the security header to the provider.
 */
@Test
public void testSaml1TokenWithRoles() throws Exception {
    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
    outProperties.put(ConfigurationConstants.USER, "alice");
    outProperties.put("password", "password");
    outProperties.put(ConfigurationConstants.SIG_PROP_FILE, "alice.properties");
    SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler();
    callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
    callbackHandler.setSignAssertion(true);
    callbackHandler.setStatement(Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);
    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_SIGNED);
    inProperties.put(ConfigurationConstants.SIG_VER_PROP_FILE, "insecurity.properties");
    final Map<QName, Object> customMap = new HashMap<>();
    CustomSamlValidator validator = new CustomSamlValidator();
    validator.setRequireSAML1Assertion(true);
    validator.setRequireSenderVouches(false);
    validator.setRequireBearer(true);
    customMap.put(WSConstants.SAML_TOKEN, validator);
    customMap.put(WSConstants.SAML2_TOKEN, validator);
    inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP, customMap);
    List<String> xpaths = Arrays.asList("//wsse:Security", "//wsse:Security/saml1:Assertion");
    Map<String, String> inMessageProperties = new HashMap<>();
    inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION, "false");
    Message message = makeInvocation(outProperties, xpaths, inProperties, inMessageProperties);
    final List<WSHandlerResult> handlerResults = CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
    SecurityContext sc = message.get(SecurityContext.class);
    assertNotNull(sc);
    assertTrue(sc.isUserInRole("user"));
    assertTrue(sc.isUserInRole("admin"));
    WSSecurityEngineResult actionResult = handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
    SamlAssertionWrapper receivedAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(receivedAssertion != null && receivedAssertion.getSaml1() != null);
    assertTrue(receivedAssertion.isSigned());
}
Also used : Message(org.apache.cxf.message.Message) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SOAPMessage(javax.xml.soap.SOAPMessage) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) SecurityContext(org.apache.cxf.security.SecurityContext) AbstractSecurityTest(org.apache.cxf.ws.security.wss4j.AbstractSecurityTest) Test(org.junit.Test)

Example 64 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class DefaultLogEventMapper method getPrincipal.

private String getPrincipal(Message message) {
    String principal = getJAASPrincipal();
    if (principal != null) {
        return principal;
    }
    SecurityContext sc = message.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        return sc.getUserPrincipal().getName();
    }
    AuthorizationPolicy authPolicy = message.get(AuthorizationPolicy.class);
    if (authPolicy != null) {
        return authPolicy.getUserName();
    }
    return null;
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) SecurityContext(org.apache.cxf.security.SecurityContext)

Example 65 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class OAuthRequestFilter method validateRequest.

protected void validateRequest(Message m) {
    if (isCorsRequest(m)) {
        return;
    }
    // Get the scheme and its data, Bearer only is supported by default
    // WWW-Authenticate with the list of supported schemes will be sent back
    // if the scheme is not accepted
    String[] authParts = getAuthorizationParts(m);
    if (authParts.length < 2) {
        throw ExceptionUtils.toForbiddenException(null, null);
    }
    String authScheme = authParts[0];
    String authSchemeData = authParts[1];
    // Get the access token
    AccessTokenValidation accessTokenV = getAccessTokenValidation(authScheme, authSchemeData, null);
    if (!accessTokenV.isInitialValidationSuccessful()) {
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    // Check audiences
    String validAudience = validateAudiences(accessTokenV.getAudiences());
    // Check if token was issued by the supported issuer
    if (issuer != null && !issuer.equals(accessTokenV.getTokenIssuer())) {
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    // Find the scopes which match the current request
    List<OAuthPermission> permissions = accessTokenV.getTokenScopes();
    List<OAuthPermission> matchingPermissions = new ArrayList<>();
    HttpServletRequest req = getMessageContext().getHttpServletRequest();
    for (OAuthPermission perm : permissions) {
        boolean uriOK = checkRequestURI(req, perm.getUris(), m);
        boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
        boolean scopeOk = checkScopeProperty(perm.getPermission());
        if (uriOK && verbOK && scopeOk) {
            matchingPermissions.add(perm);
        }
    }
    if (!permissions.isEmpty() && matchingPermissions.isEmpty() || allPermissionsMatch && (matchingPermissions.size() != permissions.size()) || !requiredScopes.isEmpty() && requiredScopes.size() != matchingPermissions.size()) {
        String message = "Client has no valid permissions";
        LOG.warning(message);
        throw ExceptionUtils.toForbiddenException(null, null);
    }
    if (accessTokenV.getClientIpAddress() != null) {
        String remoteAddress = getMessageContext().getHttpServletRequest().getRemoteAddr();
        if (remoteAddress == null || accessTokenV.getClientIpAddress().equals(remoteAddress)) {
            String message = "Client IP Address is invalid";
            LOG.warning(message);
            throw ExceptionUtils.toForbiddenException(null, null);
        }
    }
    if (blockPublicClients && !accessTokenV.isClientConfidential()) {
        String message = "Only Confidential Clients are supported";
        LOG.warning(message);
        throw ExceptionUtils.toForbiddenException(null, null);
    }
    if (am != null && !am.equals(accessTokenV.getTokenSubject().getAuthenticationMethod())) {
        String message = "The token has been authorized by the resource owner " + "using an unsupported authentication method";
        LOG.warning(message);
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    // Check Client Certificate Binding if any
    String certThumbprint = accessTokenV.getExtraProps().get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
    if (certThumbprint != null) {
        TLSSessionInfo tlsInfo = getTlsSessionInfo();
        X509Certificate cert = tlsInfo == null ? null : OAuthUtils.getRootTLSCertificate(tlsInfo);
        if (cert == null || !OAuthUtils.compareCertificateThumbprints(cert, certThumbprint)) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
    // Create the security context and make it available on the message
    SecurityContext sc = createSecurityContext(req, accessTokenV);
    m.put(SecurityContext.class, sc);
    // Also set the OAuthContext
    OAuthContext oauthContext = new OAuthContext(accessTokenV.getTokenSubject(), accessTokenV.getClientSubject(), matchingPermissions, accessTokenV.getTokenGrantType());
    oauthContext.setClientId(accessTokenV.getClientId());
    oauthContext.setClientConfidential(accessTokenV.isClientConfidential());
    oauthContext.setTokenKey(accessTokenV.getTokenKey());
    oauthContext.setTokenAudience(validAudience);
    oauthContext.setTokenIssuer(accessTokenV.getTokenIssuer());
    oauthContext.setTokenRequestParts(authParts);
    oauthContext.setTokenExtraProperties(accessTokenV.getExtraProps());
    m.setContent(OAuthContext.class, oauthContext);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) ArrayList(java.util.ArrayList) SecurityContext(org.apache.cxf.security.SecurityContext) OAuthContext(org.apache.cxf.rs.security.oauth2.common.OAuthContext) AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation) TLSSessionInfo(org.apache.cxf.security.transport.TLSSessionInfo) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SecurityContext (org.apache.cxf.security.SecurityContext)76 Principal (java.security.Principal)26 Message (org.apache.cxf.message.Message)16 Subject (javax.security.auth.Subject)13 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)12 DefaultSecurityContext (org.apache.cxf.interceptor.security.DefaultSecurityContext)11 SimplePrincipal (org.apache.cxf.common.security.SimplePrincipal)10 Test (org.junit.Test)10 SAMLSecurityContext (org.apache.cxf.rt.security.saml.claims.SAMLSecurityContext)9 WSHandlerResult (org.apache.wss4j.dom.handler.WSHandlerResult)9 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)8 LoginSecurityContext (org.apache.cxf.security.LoginSecurityContext)7 ArrayList (java.util.ArrayList)6 QName (javax.xml.namespace.QName)6 SecurityToken (org.apache.cxf.common.security.SecurityToken)6 HashMap (java.util.HashMap)5 MessageImpl (org.apache.cxf.message.MessageImpl)5 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)5 Element (org.w3c.dom.Element)5 Method (java.lang.reflect.Method)4