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;
}
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);
}
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());
}
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;
}
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);
}
Aggregations