org.opensaml.saml2.core.AuthnStatement Java Examples

The following examples show how to use org.opensaml.saml2.core.AuthnStatement. 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: AuthnStatementMarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    AuthnStatement authnStatement = (AuthnStatement) samlObject;

    if (authnStatement.getAuthnInstant() != null) {
        String authnInstantStr = Configuration.getSAMLDateFormatter().print(authnStatement.getAuthnInstant());
        domElement.setAttributeNS(null, AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME, authnInstantStr);
    }

    if (authnStatement.getSessionIndex() != null) {
        domElement.setAttributeNS(null, AuthnStatement.SESSION_INDEX_ATTRIB_NAME, authnStatement.getSessionIndex());
    }

    if (authnStatement.getSessionNotOnOrAfter() != null) {
        String sessionNotOnOrAfterStr = Configuration.getSAMLDateFormatter().print(
                authnStatement.getSessionNotOnOrAfter());
        domElement.setAttributeNS(null, AuthnStatement.SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME, sessionNotOnOrAfterStr);
    }
}
 
Example #2
Source File: AuthnStatementGenerator.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public AuthnStatement generateAuthnStatement(DateTime authnInstant) {
	//Response/Assertion/AuthnStatement/AuthContext/AuthContextClassRef
	AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
	//urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
	authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);

	//Response/Assertion/AuthnStatement/AuthContext
	AuthnContext authnContext = new AuthnContextBuilder().buildObject();
	authnContext.setAuthnContextClassRef(authnContextClassRef);

	//Response/Assertion/AuthnStatement
	AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
	authnStatement.setAuthnContext(authnContext);
	authnStatement.setAuthnInstant(authnInstant);
	logger.debug("generateAuthnStatement authnInstant "+authnInstant);
	return authnStatement;

}
 
Example #3
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 6 votes vote down vote up
private Assertion createAssertion(final DateTime issueDate, Subject subject, Issuer issuer, AuthnStatement authnStatement,
		                          AttributeStatement attributeStatement) {
	AssertionBuilder assertionBuilder = new AssertionBuilder();
	Assertion assertion = assertionBuilder.buildObject();
	assertion.setID(UUID.randomUUID().toString());
	assertion.setIssueInstant(issueDate);
	assertion.setSubject(subject);
	assertion.setIssuer(issuer);
	
	if (authnStatement != null)
		assertion.getAuthnStatements().add(authnStatement);
	
	if (attributeStatement != null)
		assertion.getAttributeStatements().add(attributeStatement);
	
	return assertion;
}
 
Example #4
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 6 votes vote down vote up
private AuthnStatement createAuthnStatement(final DateTime issueDate) {
	// create authcontextclassref object
	AuthnContextClassRefBuilder classRefBuilder = new AuthnContextClassRefBuilder();
	AuthnContextClassRef classRef = classRefBuilder.buildObject();
	classRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
	
	// create authcontext object
	AuthnContextBuilder authContextBuilder = new AuthnContextBuilder();
	AuthnContext authnContext = authContextBuilder.buildObject();
	authnContext.setAuthnContextClassRef(classRef);
	
	// create authenticationstatement object
	AuthnStatementBuilder authStatementBuilder = new AuthnStatementBuilder();
	AuthnStatement authnStatement = authStatementBuilder.buildObject();
	authnStatement.setAuthnInstant(issueDate);
	authnStatement.setAuthnContext(authnContext);
	
	return authnStatement;
}
 
Example #5
Source File: AuthnStatementUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    AuthnStatement authnStatement = (AuthnStatement) parentObject;
    if (childObject instanceof SubjectLocality) {
        authnStatement.setSubjectLocality((SubjectLocality) childObject);
    } else if (childObject instanceof AuthnContext) {
        authnStatement.setAuthnContext((AuthnContext) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #6
Source File: AuthnStatementUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    AuthnStatement authnStatement = (AuthnStatement) samlObject;
    if (attribute.getLocalName().equals(AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        authnStatement.setAuthnInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(AuthnStatement.SESSION_INDEX_ATTRIB_NAME)) {
        authnStatement.setSessionIndex(attribute.getValue());
    } else if (attribute.getLocalName().equals(AuthnStatement.SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        authnStatement.setSessionNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #7
Source File: SAML2SSOUIAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Read the session index from a Response
 *
 * @param response SAML Response
 * @return Session Index value contained in the Response
 */
private String getSessionIndexFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    String sessionIndex = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the first one
        List<AuthnStatement> authnStatements = assertions.get(0).getAuthnStatements();
        if (authnStatements != null && authnStatements.size() > 0) {
            // There can be only one authentication stmt inside the SAML assertion of a SAML Response
            AuthnStatement authStmt = authnStatements.get(0);
            sessionIndex = authStmt.getSessionIndex();
        }
    }
    return sessionIndex;
}
 
Example #8
Source File: SAML2LoginAPIAuthenticatorCmdTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private Response buildMockResponse() throws Exception {
    Response samlMessage = new ResponseBuilder().buildObject();
    samlMessage.setID("foo");
    samlMessage.setVersion(SAMLVersion.VERSION_20);
    samlMessage.setIssueInstant(new DateTime(0));
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("MockedIssuer");
    samlMessage.setIssuer(issuer);
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = new StatusCodeBuilder().buildObject();
    statusCode.setValue(StatusCode.SUCCESS_URI);
    status.setStatusCode(statusCode);
    samlMessage.setStatus(status);
    Assertion assertion = new AssertionBuilder().buildObject();
    Subject subject = new SubjectBuilder().buildObject();
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue("SOME-UNIQUE-ID");
    nameID.setFormat(NameIDType.PERSISTENT);
    subject.setNameID(nameID);
    assertion.setSubject(subject);
    AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
    authnStatement.setSessionIndex("Some Session String");
    assertion.getAuthnStatements().add(authnStatement);
    AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
    assertion.getAttributeStatements().add(attributeStatement);
    samlMessage.getAssertions().add(assertion);
    return samlMessage;
}
 
Example #9
Source File: AuthnStatementSchemaValidator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void validate(AuthnStatement authnStatement) throws ValidationException {
    validateAuthnInstant(authnStatement);
    validateAuthnContext(authnStatement);
}
 
Example #10
Source File: AssertionImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public List<AuthnStatement> getAuthnStatements() {
    QName statementQName = new QName(SAMLConstants.SAML20_NS, AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME,
            SAMLConstants.SAML20_PREFIX);
    return (List<AuthnStatement>) statements.subList(statementQName);
}
 
Example #11
Source File: AuthnStatementBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public AuthnStatement buildObject() {
    return buildObject(SAMLConstants.SAML20_NS, AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME,
            SAMLConstants.SAML20_PREFIX);
}
 
Example #12
Source File: AuthnStatementBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public AuthnStatement buildObject(String namespaceURI, String localName, String namespacePrefix) {
    return new AuthnStatementImpl(namespaceURI, localName, namespacePrefix);
}
 
Example #13
Source File: SAMLSSORelyingPartyObject.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Set the current session as authenticated by mapping with current session id to session index.
 *
 * @param cx
 * @param thisObj
 * @param args    -args[0]- current session id, args[1]-SAML response
 * @param funObj
 * @throws Exception
 */
public static void jsFunction_setSessionAuthenticated(Context cx, Scriptable thisObj,
                                                      Object[] args,
                                                      Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 2 || !(args[0] instanceof String) || !(args[1] instanceof String)) {
        throw new ScriptException("Invalid argument. Current session id and SAML response are missing.");
    }
    String decodedString = Util.decode((String) args[1]);
    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    XMLObject samlObject = Util.unmarshall(decodedString);
    String sessionIndex = null;
    String username = null;
    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;
        List<Assertion> assertions = samlResponse.getAssertions();

        // extract the session index
        if (assertions != null && assertions.size() > 0) {
            List<AuthnStatement> authenticationStatements = assertions.get(0).getAuthnStatements();
            AuthnStatement authnStatement = authenticationStatements.get(0);
            if (authnStatement != null) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndex = authnStatement.getSessionIndex();
                }
            }
        }

        // extract the username
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
    }
    if (sessionIndex == null) {
        throw new Exception("Failed to get session index from authentication statement in SAML response.");
    }
    if (username == null) {
        throw new Exception("Failed to get subject assertion from SAML response.");
    }

    SessionInfo sessionInfo = new SessionInfo((String) args[0]);
    sessionInfo.setSessionIndex(sessionIndex);
    sessionInfo.setLoggedInUser(username);
    sessionInfo.setSamlToken((String) args[1]);//We expect an encoded SamlToken here.
    relyingPartyObject.addSessionInfo(sessionInfo);

}
 
Example #14
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 4 votes vote down vote up
public Response createSAMLResponse(final String subjectId, final DateTime authenticationTime,
		                           final String credentialType, final HashMap<String, List<String>> attributes, String issuer, Integer samlAssertionDays) {
	
	try {
		DefaultBootstrap.bootstrap();
		
		Signature signature = createSignature();
		Status status = createStatus();
		Issuer responseIssuer = null;
		Issuer assertionIssuer = null;
		Subject subject = null;
		AttributeStatement attributeStatement = null;
		
		if (issuer != null) {
			responseIssuer = createIssuer(issuer);
			assertionIssuer = createIssuer(issuer);
		}
		
		if (subjectId != null) {
			subject = createSubject(subjectId, samlAssertionDays);
		}
		
		if (attributes != null && attributes.size() != 0) {
			attributeStatement = createAttributeStatement(attributes);
		}
		
		AuthnStatement authnStatement = createAuthnStatement(authenticationTime);
		
		Assertion assertion = createAssertion(new DateTime(), subject, assertionIssuer, authnStatement, attributeStatement);
		
		Response response = createResponse(new DateTime(), responseIssuer, status, assertion);
		response.setSignature(signature);
		
		ResponseMarshaller marshaller = new ResponseMarshaller();
		Element element = marshaller.marshall(response);
		
		if (signature != null) {
			Signer.signObject(signature);
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XMLHelper.writeNode(element, baos);
	
		return response;
		
	} catch (Throwable t) {
		t.printStackTrace();
		return null;
	}
}
 
Example #15
Source File: AuthnStatementSchemaValidator.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Checks that the AuthnInstant attribute is present.
 * 
 * @param authnStatement
 * @throws ValidationException
 */
protected void validateAuthnInstant(AuthnStatement authnStatement) throws ValidationException {
    if (authnStatement.getAuthnInstant() == null) {
        throw new ValidationException("AuthnInstant required");
    }
}
 
Example #16
Source File: AuthnStatementSchemaValidator.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Checks that the AuthnContext element is present.
 * 
 * @param authnStatement
 * @throws ValidationException
 */
protected void validateAuthnContext(AuthnStatement authnStatement) throws ValidationException {
    if (authnStatement.getAuthnContext() == null) {
        throw new ValidationException("AuthnContext required");
    }
}