org.apache.cxf.security.SecurityContext Java Examples

The following examples show how to use org.apache.cxf.security.SecurityContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecureAnnotationsInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    method = TestService.class.getMethod("echo", new Class[]{});
    message.put(SecurityContext.class, new TestSecurityContext());
    Exchange ex = new ExchangeImpl();
    message.setExchange(ex);

    Service service = EasyMock.createMock(Service.class);
    ex.put(Service.class, service);
    MethodDispatcher md = EasyMock.createMock(MethodDispatcher.class);
    EasyMock.expect(service.get(MethodDispatcher.class.getName())).andReturn(md);

    BindingOperationInfo boi = EasyMock.createMock(BindingOperationInfo.class);
    ex.put(BindingOperationInfo.class, boi);
    EasyMock.expect(md.getMethod(boi)).andReturn(method);
    EasyMock.replay(service, md);
}
 
Example #2
Source File: AbstractSecurityContextInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) {
    SecurityToken token = message.get(SecurityToken.class);
    if (token == null) {
        reportSecurityException("Security Token is not available on the current message");
    }

    SecurityContext context = message.get(SecurityContext.class);
    if (context == null || context.getUserPrincipal() == null) {
        reportSecurityException("User Principal is not available on the current message");
    }

    Subject subject = null;
    try {
        subject = createSubject(token);
    } catch (Exception ex) {
        reportSecurityException("Failed Authentication : Subject has not been created, "
                                + ex.getMessage());
    }
    if (subject == null || subject.getPrincipals().isEmpty()) {
        reportSecurityException("Failed Authentication : Invalid Subject");
    }

    Principal principal = getPrincipal(context.getUserPrincipal(), subject);
    SecurityContext sc = createSecurityContext(principal, subject);
    message.put(SecurityContext.class, sc);
}
 
Example #3
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;
    
    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());
    
    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example #4
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;
    
    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());
    
    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example #5
Source File: RESTSecurityTokenServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected Principal getPrincipal() {
    // Try JAX-RS SecurityContext first
    if (securityContext != null && securityContext.getUserPrincipal() != null) {
        return securityContext.getUserPrincipal();
    }

    // Then try the CXF SecurityContext
    SecurityContext sc = (SecurityContext)messageContext.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        return sc.getUserPrincipal();
    }

    // Get the TLS client principal if no security context is set up
    X509Certificate clientCert = getTLSClientCertificate();
    if (clientCert != null) {
        return clientCert.getSubjectX500Principal();
    }

    return null;
}
 
Example #6
Source File: AbstractServiceProviderFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void setSecurityContext(Message m, SamlAssertionWrapper assertionWrapper) {
    Subject subject = SAMLUtils.getSubject(m, assertionWrapper);
    final String name = subject.getName();

    if (name != null) {
        String roleAttributeName =
            (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, m);
        if (roleAttributeName == null || roleAttributeName.length() == 0) {
            roleAttributeName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role";
        }
        ClaimCollection claims =
            org.apache.cxf.rt.security.saml.utils.SAMLUtils.getClaims(assertionWrapper);
        Set<Principal> roles =
            org.apache.cxf.rt.security.saml.utils.SAMLUtils.parseRolesFromClaims(
                claims, roleAttributeName, null);

        SAMLSecurityContext context =
            new SAMLSecurityContext(new SimplePrincipal(name), roles, claims);
        context.setIssuer(org.apache.cxf.rt.security.saml.utils.SAMLUtils.getIssuer(assertionWrapper));
        context.setAssertionElement(
            org.apache.cxf.rt.security.saml.utils.SAMLUtils.getAssertionElement(assertionWrapper));
        m.put(SecurityContext.class, context);
    }
}
 
Example #7
Source File: OAuthRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected SecurityContext createSecurityContext(HttpServletRequest request,
                                                AccessTokenValidation accessTokenV) {
    UserSubject resourceOwnerSubject = accessTokenV.getTokenSubject();
    UserSubject clientSubject = accessTokenV.getClientSubject();

    final UserSubject theSubject =
        OAuthRequestFilter.this.useUserSubject ? resourceOwnerSubject : clientSubject;

    return new SecurityContext() {

        public Principal getUserPrincipal() {
            return theSubject != null ? new SimplePrincipal(theSubject.getLogin()) : null;
        }

        public boolean isUserInRole(String role) {
            if (theSubject == null) {
                return false;
            }
            return theSubject.getRoles().contains(role);
        }
    };
}
 
Example #8
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;
    
    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());
    
    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example #9
Source File: DefaultLogEventMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;

    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());

    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example #11
Source File: AuthorizationHandler.java    From geofence with GNU General Public License v2.0 6 votes vote down vote up
protected boolean authorize(SecurityContext sc, Method method)
{
    List<String> expectedRoles = getExpectedRoles(method);
    if (expectedRoles.isEmpty())
    {

        List<String> denyRoles = getDenyRoles(method);

        return denyRoles.isEmpty() ? true : isUserInRole(sc, denyRoles, true);
    }

    if (isUserInRole(sc, expectedRoles, false))
    {
        return true;
    }
    if (sc.getUserPrincipal() != null)
    {
        LOGGER.error(sc.getUserPrincipal().getName() + " is not authorized");
    }

    return false;
}
 
Example #12
Source File: JMSConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Process the reply message
 * @throws JMSException
 */
protected void processReplyMessage(Exchange exchange, javax.jms.Message jmsMessage) throws JMSException {

    LOG.log(Level.FINE, "client received reply: ", jmsMessage);
    try {
        Message inMessage = JMSMessageUtils.asCXFMessage(jmsMessage,
                                                         JMSConstants.JMS_CLIENT_RESPONSE_HEADERS);
        if (jmsConfig.isCreateSecurityContext()) {
            SecurityContext securityContext = SecurityContextFactory.buildSecurityContext(jmsMessage, jmsConfig);
            inMessage.put(SecurityContext.class, securityContext);
        }
        exchange.setInMessage(inMessage);
        Object responseCode = inMessage.get(org.apache.cxf.message.Message.RESPONSE_CODE);
        exchange.put(org.apache.cxf.message.Message.RESPONSE_CODE, responseCode);

        if (exchange.isSynchronous()) {
            synchronized (exchange) {
                exchange.put(CORRELATED, Boolean.TRUE);
                exchange.notifyAll();
            }
        }

        if (incomingObserver != null) {
            incomingObserver.onMessage(exchange.getInMessage());
        }
    } catch (UnsupportedEncodingException ex) {
        getLogger().log(Level.WARNING, "can't get the right encoding information " + ex);
    }
}
 
Example #13
Source File: ValidateTokenTransformationUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
        public Principal getUserPrincipal() {
            return p;
        }
        public boolean isUserInRole(String role) {
            return false;
        }
    };
}
 
Example #14
Source File: RedirectionBasedGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected SecurityContext getAndValidateSecurityContext(MultivaluedMap<String, String> params) {
    SecurityContext securityContext =
        (SecurityContext)getMessageContext().get(SecurityContext.class.getName());
    if (securityContext == null || securityContext.getUserPrincipal() == null) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    checkTransportSecurity();
    return securityContext;
}
 
Example #15
Source File: ValidateJWTUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
        public Principal getUserPrincipal() {
            return p;
        }
        public boolean isUserInRole(String role) {
            return false;
        }
    };
}
 
Example #16
Source File: JwsContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final String content = IOUtils.readStringFromStream(context.getEntityStream());
    if (StringUtils.isEmpty(content)) {
        return;
    }
    JwsCompactConsumer p = new JwsCompactConsumer(content);
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders());
    if (!p.verifySignatureWith(theSigVerifier)) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }
    JoseUtils.validateRequestContextProperty(p.getJwsHeaders());
    
    byte[] bytes = p.getDecodedJwsPayloadBytes();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));

    String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }

    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), p.getJwsHeaders());
    }
    
    Principal currentPrincipal = context.getSecurityContext().getUserPrincipal();
    if (currentPrincipal == null || currentPrincipal.getName() == null) {
        SecurityContext securityContext = configureSecurityContext(theSigVerifier);
        if (securityContext != null) {
            JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext);
        }
    }
}
 
Example #17
Source File: IssueOnbehalfofUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
        public Principal getUserPrincipal() {
            return p;
        }
        public boolean isUserInRole(String role) {
            return false;
        }
    };
}
 
Example #18
Source File: IssueJWTUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
        public Principal getUserPrincipal() {
            return p;
        }
        public boolean isUserInRole(String role) {
            return false;
        }
    };
}
 
Example #19
Source File: CancelSCTUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
        public Principal getUserPrincipal() {
            return p;
        }
        public boolean isUserInRole(String role) {
            return false;
        }
    };
}
 
Example #20
Source File: RedirectionBasedGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected UserSubject createUserSubject(SecurityContext securityContext,
                                        MultivaluedMap<String, String> params) {
    if (subjectCreator != null) {
        UserSubject subject = subjectCreator.createUserSubject(getMessageContext(),
                                                   params);
        if (subject != null) {
            return subject;
        }
    }
    return OAuthUtils.createSubject(getMessageContext(), securityContext);
}
 
Example #21
Source File: ValidateSamlUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
        public Principal getUserPrincipal() {
            return p;
        }
        public boolean isUserInRole(String role) {
            return false;
        }
    };
}
 
Example #22
Source File: SamlTokenTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecurityContext testSaml1Token(boolean allowUnsignedPrincipal) throws Exception {
    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, new SAML1CallbackHandler());

    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    final Map<QName, Object> customMap = new HashMap<>();
    CustomSamlValidator validator = new CustomSamlValidator();
    customMap.put(WSConstants.SAML_TOKEN, validator);
    customMap.put(WSConstants.SAML2_TOKEN, validator);
    inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP, customMap);

    List<String> xpaths = new ArrayList<>();
    xpaths.add("//wsse:Security");
    xpaths.add("//wsse:Security/saml1:Assertion");

    Map<String, String> inMessageProperties = new HashMap<>();
    if (allowUnsignedPrincipal) {
        inMessageProperties.put(SecurityConstants.ENABLE_UNSIGNED_SAML_ASSERTION_PRINCIPAL, "true");
    }

    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));

    WSSecurityEngineResult actionResult =
        handlerResults.get(0).getActionResults().get(WSConstants.ST_UNSIGNED).get(0);
    SamlAssertionWrapper receivedAssertion =
        (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(receivedAssertion != null && receivedAssertion.getSaml1() != null);
    assertFalse(receivedAssertion.isSigned());

    return message.get(SecurityContext.class);
}
 
Example #23
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected SecurityContext createSecurityContext(final Principal p) {
    Message msg = PhaseInterceptorChain.getCurrentMessage();
    if (msg == null) {
        throw new IllegalStateException("Current message is not available");
    }
    return new DefaultSecurityContext(p, msg.get(Subject.class));
}
 
Example #24
Source File: AuthorizationHandler.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
protected boolean isUserInRole(SecurityContext sc, List<String> roles, boolean deny)
    {
//      System.out.println("::::::::::::::::::::::::  0");
//        if (!isUserAllRole(sc, roles, deny)) {
//              System.out.println("::::::::::::::::::::::::  1");
//            return false;
//        }

        // Additional check.
        if (!userRolesMap.isEmpty())
        {
            List<String> userRoles = userRolesMap.get(sc.getUserPrincipal().getName());
            if (userRoles == null)
            {
                return false;
            }
            for (String role : roles)
            {
                if (userRoles.contains(role))
                {
                    return true;
                }
            }

            return false;
        }
        else
        {
            return true;
        }
    }
 
Example #25
Source File: OperationInfoAuthorizingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean authorize(SecurityContext sc, String key) {
    List<String> expectedRoles = getExpectedRoles(key);
    if (expectedRoles.isEmpty()) {
        List<String> denyRoles = getDenyRoles(key);
        return denyRoles.isEmpty() || isUserInRole(sc, denyRoles, true);
    }

    if (isUserInRole(sc, expectedRoles, false)) {
        return true;
    }
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine(sc.getUserPrincipal().getName() + " is not authorized");
    }
    return false;
}
 
Example #26
Source File: JAASLoginInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected SecurityContext createSecurityContext(String name, Subject subject) {
    if (getRoleClassifier() != null) {
        return new RolePrefixSecurityContextImpl(subject, getRoleClassifier(),
                                                 getRoleClassifierType());
    }
    return new DefaultSecurityContext(name, subject);
}
 
Example #27
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
protected SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {

        public Principal getUserPrincipal() {
            return p;
        }

        public boolean isUserInRole(String arg0) {
            return false;
        }
    };
}
 
Example #28
Source File: AbstractXmlSigInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String getUserName(Crypto crypto, Message message) {
    SecurityContext sc = message.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        return sc.getUserPrincipal().getName();
    }
    return RSSecurityUtils.getUserName(crypto, null);

}
 
Example #29
Source File: SamlTokenInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void processSamlToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element)h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if ("Assertion".equals(child.getLocalName())) {
            try {
                List<WSSecurityEngineResult> samlResults = processToken(child, message);
                if (samlResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>)message
                            .get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<WSHandlerResult>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, samlResults);
                    results.add(0, rResult);

                    assertSamlTokens(message);
                    
                    Principal principal = 
                        (Principal)samlResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
                    message.put(WSS4JInInterceptor.PRINCIPAL_RESULT, principal);                   
                    
                    SecurityContext sc = message.get(SecurityContext.class);
                    if (sc == null || sc.getUserPrincipal() == null) {
                        message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                    }

                }
            } catch (WSSecurityException ex) {
                throw new Fault(ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
 
Example #30
Source File: BasicAuthFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {

        public Principal getUserPrincipal() {
            return p;
        }

        public boolean isUserInRole(String arg0) {
            return false;
        }
    };
}