Java源码示例:org.apache.wss4j.common.saml.SamlAssertionWrapper
示例1
public void validate(Message message, SamlAssertionWrapper wrapper) {
validateSAMLVersion(wrapper);
Conditions cs = wrapper.getSaml2().getConditions();
validateAudience(message, cs);
if (issuer != null) {
String actualIssuer = getIssuer(wrapper);
String expectedIssuer = OAuthConstants.CLIENT_ID.equals(issuer)
? wrapper.getSaml2().getSubject().getNameID().getValue() : issuer;
if (actualIssuer == null || !actualIssuer.equals(expectedIssuer)) {
throw ExceptionUtils.toNotAuthorizedException(null, null);
}
}
if (!validateAuthenticationSubject(message, cs, wrapper.getSaml2().getSubject())) {
throw ExceptionUtils.toNotAuthorizedException(null, null);
}
}
示例2
public static String createToken(String audRestr, boolean saml2, boolean sign)
throws WSSecurityException {
SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(sign);
samlCallbackHandler.setAudience(audRestr);
if (!saml2) {
samlCallbackHandler.setSaml2(false);
samlCallbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
}
SAMLCallback samlCallback = new SAMLCallback();
SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
if (samlCallback.isSignAssertion()) {
samlAssertion.signAssertion(
samlCallback.getIssuerKeyName(),
samlCallback.getIssuerKeyPassword(),
samlCallback.getIssuerCrypto(),
samlCallback.isSendKeyValue(),
samlCallback.getCanonicalizationAlgorithm(),
samlCallback.getSignatureAlgorithm()
);
}
return samlAssertion.assertionToString();
}
示例3
public void handleMessage(Message message) throws Fault {
Form form = getRequestForm(message);
if (form == null) {
return;
}
try {
SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(message);
Document doc = DOMUtils.newDocument();
Element assertionElement = assertionWrapper.toDOM(doc);
String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));
updateForm(form, encodedToken);
} catch (Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
LOG.warning(sw.toString());
throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
}
}
示例4
@org.junit.Test
public void testIssuePublicKeySAML2Token() throws Exception {
WebClient client = webClient()
.path("saml2.0")
.query("keyType", STSConstants.PUBLIC_KEY_KEYTYPE)
.accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
assertNotNull(subjectKeyInfo.getCerts());
}
示例5
@org.junit.Test
public void testIssuePublicKeySAML2TokenShortKeyType() throws Exception {
WebClient client = webClient()
.path("saml2.0")
.query("keyType", "PublicKey")
.accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
assertNotNull(subjectKeyInfo.getCerts());
}
示例6
@org.junit.Test
public void testIssueBearerSAML1TokenShorKeyType() throws Exception {
WebClient client = webClient()
.path("saml1.1")
.query("keyType", "Bearer")
.accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(confirmMethod.contains("bearer"));
}
示例7
protected void checkSubjectConfirmationData(Message message, SamlAssertionWrapper assertion) {
String valSAMLSubjectConf =
(String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,
message);
boolean validateSAMLSubjectConf = true;
if (valSAMLSubjectConf != null) {
validateSAMLSubjectConf = Boolean.parseBoolean(valSAMLSubjectConf);
}
if (validateSAMLSubjectConf) {
Certificate[] tlsCerts = getTLSCertificates(message);
if (!checkHolderOfKey(message, assertion, tlsCerts)) {
throwFault("Holder Of Key claim fails", null);
}
if (!checkSenderVouches(message, assertion, tlsCerts)) {
throwFault("Sender vouchers claim fails", null);
}
if (!checkBearer(assertion, tlsCerts)) {
throwFault("Bearer claim fails", null);
}
}
}
示例8
/**
* Check the policy version against the received assertion
*/
private boolean checkVersion(
AssertionInfoMap aim,
SamlToken samlToken,
SamlAssertionWrapper assertionWrapper
) {
SamlTokenType samlTokenType = samlToken.getSamlTokenType();
if ((samlTokenType == SamlTokenType.WssSamlV11Token10
|| samlTokenType == SamlTokenType.WssSamlV11Token11)
&& assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
return false;
} else if (samlTokenType == SamlTokenType.WssSamlV20Token11
&& assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
return false;
}
if (samlTokenType != null) {
PolicyUtils.assertPolicy(aim, new QName(samlToken.getVersion().getNamespace(), samlTokenType.name()));
}
return true;
}
示例9
private Element validateSAMLSecurityTokenResponse(
RequestSecurityTokenResponseType securityResponse, boolean saml2
) throws Exception {
RequestedSecurityTokenType requestedSecurityToken = getRequestedSecurityToken(securityResponse);
assertNotNull(requestedSecurityToken);
// Process the token
List<WSSecurityEngineResult> results =
processToken((Element)requestedSecurityToken.getAny());
assertTrue(results != null && results.size() == 1);
SamlAssertionWrapper assertion =
(SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertNotNull(assertion);
if (saml2) {
assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
} else {
assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);
}
assertTrue(assertion.isSigned());
return (Element)results.get(0).get(WSSecurityEngineResult.TAG_TOKEN_ELEMENT);
}
示例10
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
WSPasswordCallback[] cb = {
new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
};
cbPasswordHandler.handle(cb);
String password = cb[0].getPassword();
if (sign) {
assertion.signAssertion(alias, password, crypto, false);
}
Document doc = STSUtil.toSOAPPart(rstr);
Element token = assertion.toDOM(doc);
Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
FederationConstants.WS_TRUST_13_NS);
if (e == null) {
e = XMLUtils.findElement(doc, "RequestedSecurityToken",
FederationConstants.WS_TRUST_2005_02_NS);
}
e.appendChild(token);
return DOM2Writer.nodeToString(doc);
}
示例11
/**
* Verify trust in the signature of a signed Assertion. This method is separate so that
* the user can override if if they want.
* @param assertion The signed Assertion
* @param data The RequestData context
* @return A Credential instance
* @throws WSSecurityException
*/
@Override
protected Credential verifySignedAssertion(
SamlAssertionWrapper assertion,
RequestData data
) throws WSSecurityException {
Credential credential = new Credential();
SAMLKeyInfo samlKeyInfo = assertion.getSignatureKeyInfo();
credential.setPublicKey(samlKeyInfo.getPublicKey());
credential.setCertificates(samlKeyInfo.getCerts());
FedizSignatureTrustValidator trustValidator = new FedizSignatureTrustValidator();
trustValidator.setSignatureTrustType(signatureTrustType);
trustValidator.setSubjectConstraints(subjectDNPatterns);
return trustValidator.validate(credential, data);
}
示例12
private void signAssertion(
SamlAssertionWrapper assertion,
TokenRenewerParameters tokenParameters
) throws Exception {
if (signToken) {
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
String realm = tokenParameters.getRealm();
RealmProperties samlRealm = null;
if (realm != null && realmMap.containsKey(realm)) {
samlRealm = realmMap.get(realm);
}
signToken(assertion, samlRealm, stsProperties, tokenParameters.getKeyRequirements());
} else {
if (assertion.getSaml1().getSignature() != null) {
assertion.getSaml1().setSignature(null);
} else if (assertion.getSaml2().getSignature() != null) {
assertion.getSaml2().setSignature(null);
}
}
}
示例13
private void createNewConditions(SamlAssertionWrapper assertion, TokenRenewerParameters tokenParameters) {
ConditionsBean conditions =
conditionsProvider.getConditions(convertToProviderParameters(tokenParameters));
if (assertion.getSaml1() != null) {
org.opensaml.saml.saml1.core.Assertion saml1Assertion = assertion.getSaml1();
saml1Assertion.setIssueInstant(new DateTime());
org.opensaml.saml.saml1.core.Conditions saml1Conditions =
SAML1ComponentBuilder.createSamlv1Conditions(conditions);
saml1Assertion.setConditions(saml1Conditions);
} else {
org.opensaml.saml.saml2.core.Assertion saml2Assertion = assertion.getSaml2();
saml2Assertion.setIssueInstant(new DateTime());
org.opensaml.saml.saml2.core.Conditions saml2Conditions =
SAML2ComponentBuilder.createConditions(conditions);
saml2Assertion.setConditions(saml2Conditions);
}
}
示例14
/**
* Store a SAML Assertion as a SecurityToken
*/
protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) throws TokenStoreException {
String id = findIDFromSamlToken(assertion.getElement());
if (id == null) {
return;
}
SecurityToken secToken = new SecurityToken(id);
if (assertion.getSaml2() != null) {
secToken.setTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
} else {
secToken.setTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
}
secToken.setToken(assertion.getElement());
getTokenStore().add(secToken);
message.put(SecurityConstants.TOKEN_ID, secToken.getId());
}
示例15
public void handleMessage(Message message) throws Fault {
try {
SamlAssertionWrapper assertionWrapper = createAssertion(message);
Document doc = DOMUtils.newDocument();
Element assertionElement = assertionWrapper.toDOM(doc);
String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));
Map<String, List<String>> headers = getHeaders(message);
StringBuilder builder = new StringBuilder();
builder.append("SAML").append(' ').append(encodedToken);
headers.put("Authorization",
CastUtils.cast(Collections.singletonList(builder.toString()), String.class));
} catch (Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
LOG.warning(sw.toString());
throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
}
}
示例16
protected UserSubject getGrantSubject(Message message, SamlAssertionWrapper wrapper) {
SecurityContext sc = scProvider.getSecurityContext(message, wrapper);
if (sc instanceof SAMLSecurityContext) {
SAMLSecurityContext jaxrsSc = (SAMLSecurityContext)sc;
Set<Principal> rolesP = jaxrsSc.getUserRoles();
List<String> roles = new ArrayList<>();
if (rolesP != null) {
for (Principal p : rolesP) {
roles.add(p.getName());
}
}
return new SamlUserSubject(jaxrsSc.getUserPrincipal().getName(),
roles,
jaxrsSc.getClaims());
}
return new UserSubject(sc.getUserPrincipal().getName());
}
示例17
/**
* Check the policy version against the received assertion
*/
private boolean checkVersion(
AssertionInfoMap aim,
SamlToken samlToken,
SamlAssertionWrapper assertionWrapper
) {
SamlTokenType tokenType = samlToken.getSamlTokenType();
if ((tokenType == SamlTokenType.WssSamlV11Token10
|| tokenType == SamlTokenType.WssSamlV11Token11)
&& assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
return false;
} else if (tokenType == SamlTokenType.WssSamlV20Token11
&& assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
return false;
}
PolicyUtils.assertPolicy(aim, new QName(samlToken.getVersion().getNamespace(), tokenType.name()));
return true;
}
示例18
private String createSamlResponseStr(AbstractSAMLCallbackHandler saml2CallbackHandler,
String requestId,
boolean signAssertion) throws Exception {
ConditionsBean cp = new ConditionsBean();
AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
audienceRestriction.getAudienceURIs().add(TEST_REQUEST_URL);
cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
saml2CallbackHandler.setConditions(cp);
// Subject Confirmation Data
SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
subjectConfirmationData.setInResponseTo(requestId);
subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
saml2CallbackHandler.setSubjectConfirmationData(subjectConfirmationData);
SAMLCallback samlCallback = new SAMLCallback();
SAMLUtil.doSAMLCallback(saml2CallbackHandler, samlCallback);
SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
Element response = createEncryptedSamlResponse(assertion, "mystskey", signAssertion, requestId);
return encodeResponse(response);
}
示例19
private SecurityContext createSecurityContext(Message msg,
SamlAssertionWrapper samlAssertion) {
String roleAttributeName =
(String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
if (roleAttributeName == null || roleAttributeName.length() == 0) {
roleAttributeName = WSS4JInInterceptor.SAML_ROLE_ATTRIBUTENAME_DEFAULT;
}
ClaimCollection claims =
SAMLUtils.getClaims(samlAssertion);
Set<Principal> roles =
SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);
SAMLSecurityContext context =
new SAMLSecurityContext(new SAMLTokenPrincipalImpl(samlAssertion), roles, claims);
context.setIssuer(SAMLUtils.getIssuer(samlAssertion));
context.setAssertionElement(SAMLUtils.getAssertionElement(samlAssertion));
return context;
}
示例20
@org.junit.Test
public void testInvalidStatusCode() throws Exception {
Document doc = DOMUtils.createDocument();
Status status =
SAML2PResponseComponentBuilder.createStatus(
SAMLProtocolResponseValidator.SAML1_STATUSCODE_SUCCESS, null
);
Response response =
SAML2PResponseComponentBuilder.createSAMLResponse(
"http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
);
// Create an AuthenticationAssertion
SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
callbackHandler.setIssuer("http://cxf.apache.org/issuer");
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
SAMLCallback samlCallback = new SAMLCallback();
SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
response.getAssertions().add(assertion.getSaml2());
Element policyElement = OpenSAMLUtil.toDom(response, doc);
doc.appendChild(policyElement);
assertNotNull(policyElement);
Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);
// Validate the Response
SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
try {
validator.validateSamlResponse(marshalledResponse, null, null);
fail("Expected failure on an invalid SAML code");
} catch (WSSecurityException ex) {
// expected
}
}
示例21
/**
* Check the sender-vouches requirements against the received assertion. The SAML
* Assertion and the request body must be signed by the same signature.
*/
protected boolean checkSenderVouches(
Message message,
SamlAssertionWrapper assertionWrapper,
Certificate[] tlsCerts
) {
//
// If we have a 2-way TLS connection, then we don't have to check that the
// assertion + body are signed
// If no body is available (ex, with GET) then consider validating that
// the base64-encoded token is signed by the same signature
//
if (tlsCerts != null && tlsCerts.length > 0) {
return true;
}
List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
for (String confirmationMethod : confirmationMethods) {
if (OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {
Element signedElement = message.getContent(Element.class);
Node assertionParent = assertionWrapper.getElement().getParentNode();
// if we have a shared parent signed node then we can assume both
// this SAML assertion and the main payload have been signed by the same
// signature
if (assertionParent != signedElement) {
// if not then try to compare if the same cert/key was used to sign SAML token
// and the payload
SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSignatureKeyInfo();
if (!compareCredentials(subjectKeyInfo, message, tlsCerts)) {
return false;
}
}
}
}
return true;
}
示例22
/**
* Validate SAML 2 token which includes the role attribute with 2 values
* The configured subject of the trusted issuer doesn't match with
* the issuer of the SAML token
*/
@org.junit.Test
public void validateSAML2TokenSeveralCertStore() throws Exception {
SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
callbackHandler.setIssuer(TEST_RSTR_ISSUER);
callbackHandler.setSubjectName(TEST_USER);
ConditionsBean cp = new ConditionsBean();
AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
callbackHandler.setConditions(cp);
SAMLCallback samlCallback = new SAMLCallback();
SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
String rstr = createSamlToken(assertion, "mystskey", true);
FedizRequest wfReq = new FedizRequest();
wfReq.setAction(FederationConstants.ACTION_SIGNIN);
wfReq.setResponseToken(rstr);
// Load and update the config to enforce an error
configurator = null;
FedizContext config = getFederationConfigurator().getFedizContext("ROOT2");
FedizProcessor wfProc = new FederationProcessorImpl();
FedizResponse wfRes = wfProc.processRequest(wfReq, config);
Assert.assertEquals("Principal name wrong", TEST_USER,
wfRes.getUsername());
Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles()
.size());
}
示例23
private Document createEnvelopedSamlToken(Message message, Document payloadDoc)
throws Exception {
Element docEl = payloadDoc.getDocumentElement();
SamlAssertionWrapper assertion = SAMLUtils.createAssertion(message);
QName rootName = DOMUtils.getElementQName(payloadDoc.getDocumentElement());
if (rootName.equals(envelopeQName)) {
docEl.appendChild(assertion.toDOM(payloadDoc));
return payloadDoc;
}
Document newDoc = DOMUtils.createDocument();
Element root =
newDoc.createElementNS(envelopeQName.getNamespaceURI(),
envelopeQName.getPrefix() + ":" + envelopeQName.getLocalPart());
newDoc.appendChild(root);
Element assertionEl = assertion.toDOM(newDoc);
root.appendChild(assertionEl);
payloadDoc.removeChild(docEl);
newDoc.adoptNode(docEl);
root.appendChild(docEl);
if (signLater) {
// It appears adopting and removing nodes
// leaves some stale refs/state with adopted nodes and thus the digest ends up
// being wrong on the server side if XML sig is applied later in the enveloped mode
// TODO: this is not critical now - but figure out if we can avoid copying
// DOMs
CachedOutputStream bos = new CachedOutputStream();
StaxUtils.writeTo(newDoc, bos);
return StaxUtils.read(bos.getInputStream());
}
return newDoc;
}
示例24
/**
* "Validate" SAML 2 token with a custom token validator
* If a validator is configured it precedes the SAMLTokenValidator as part of Fediz
*/
@org.junit.Test
public void validateSAML2TokenMaxClockSkewNotDefined() throws Exception {
SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
callbackHandler.setIssuer(TEST_RSTR_ISSUER);
callbackHandler.setSubjectName(TEST_USER);
ConditionsBean cp = new ConditionsBean();
AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
callbackHandler.setConditions(cp);
SAMLCallback samlCallback = new SAMLCallback();
SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
String rstr = createSamlToken(assertion, "mystskey", true);
FedizRequest wfReq = new FedizRequest();
wfReq.setAction(FederationConstants.ACTION_SIGNIN);
wfReq.setResponseToken(rstr);
configurator = null;
FedizContext config = getFederationConfigurator().getFedizContext("NOCLOCKSKEW");
FedizProcessor wfProc = new FederationProcessorImpl();
FedizResponse wfRes = wfProc.processRequest(wfReq, config);
Assert.assertEquals("Principal name wrong", TEST_USER,
wfRes.getUsername());
Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles()
.size());
Assert.assertEquals("Audience wrong", TEST_AUDIENCE, wfRes.getAudience());
}
示例25
/**
* Validate SAML 1.1 token which includes the role attribute with 2 values
* Roles are encoded as a multi-value saml attribute
*/
@org.junit.Test
public void validateSAML1Token() throws Exception {
SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler();
callbackHandler.setStatement(SAML1CallbackHandler.Statement.ATTR);
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
callbackHandler.setIssuer(TEST_RSTR_ISSUER);
callbackHandler.setSubjectName(TEST_USER);
ConditionsBean cp = new ConditionsBean();
AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
callbackHandler.setConditions(cp);
SAMLCallback samlCallback = new SAMLCallback();
SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
String rstr = createSamlToken(assertion, "mystskey", true);
FedizRequest wfReq = new FedizRequest();
wfReq.setAction(FederationConstants.ACTION_SIGNIN);
wfReq.setResponseToken(rstr);
configurator = null;
FedizContext config = getFederationConfigurator().getFedizContext("ROOT");
FedizProcessor wfProc = new FederationProcessorImpl();
FedizResponse wfRes = wfProc.processRequest(wfReq, config);
Assert.assertEquals("Principal name wrong", TEST_USER,
wfRes.getUsername());
Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles()
.size());
Assert.assertEquals("Audience wrong", TEST_AUDIENCE, wfRes.getAudience());
assertClaims(wfRes.getClaims(), callbackHandler.getRoleAttributeName());
}
示例26
/**
* Test the Bearer SAML1 case
*/
@org.junit.Test
public void testBearerSaml1() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
// Get a token
SecurityToken token =
requestSecurityToken(SAML1_TOKEN_TYPE, BEARER_KEYTYPE, bus, DEFAULT_ADDRESS);
assertEquals(SAML1_TOKEN_TYPE, token.getTokenType());
assertNotNull(token.getToken());
// Process the token
List<WSSecurityEngineResult> results = processToken(token);
assertTrue(results != null && results.size() == 1);
SamlAssertionWrapper assertion =
(SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertNotNull(assertion);
assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
assertTrue(assertion.isSigned());
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(confirmMethod != null && confirmMethod.contains("bearer"));
bus.shutdown(true);
}
示例27
/**
* Test the Bearer SAML1 case with a Context Attribute
*/
@org.junit.Test
public void testBearerSaml1Context() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
// Get a token
String context = "AuthenticationContext";
SecurityToken token =
requestSecurityToken(SAML1_TOKEN_TYPE, BEARER_KEYTYPE, bus, DEFAULT_ADDRESS, context);
assertEquals(SAML1_TOKEN_TYPE, token.getTokenType());
assertNotNull(token.getToken());
// Process the token
List<WSSecurityEngineResult> results = processToken(token);
assertTrue(results != null && results.size() == 1);
SamlAssertionWrapper assertion =
(SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertNotNull(assertion);
assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
assertTrue(assertion.isSigned());
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(confirmMethod != null && confirmMethod.contains("bearer"));
bus.shutdown(true);
}
示例28
/**
* Test the Bearer SAML1 case with a Lifetime element
*/
@org.junit.Test
public void testBearerSaml1Lifetime() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
// Get a token
SecurityToken token =
requestSecurityTokenTTL(SAML1_TOKEN_TYPE, BEARER_KEYTYPE, bus, DEFAULT_ADDRESS);
assertEquals(SAML1_TOKEN_TYPE, token.getTokenType());
assertNotNull(token.getToken());
// Process the token
List<WSSecurityEngineResult> results = processToken(token);
assertTrue(results != null && results.size() == 1);
SamlAssertionWrapper assertion =
(SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertNotNull(assertion);
assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
assertTrue(assertion.isSigned());
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(confirmMethod != null && confirmMethod.contains("bearer"));
bus.shutdown(true);
}
示例29
@org.junit.Test
public void testIssueSAML2Token() throws Exception {
WebClient client = webClient()
.path("saml2.0")
.accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
}
示例30
@org.junit.Test
public void testIssueSAML1Token() throws Exception {
WebClient client = webClient()
.path("saml1.1")
.accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);
}