Search in sources :

Example 36 with NameIDType

use of org.keycloak.dom.saml.v2.assertion.NameIDType in project keycloak by keycloak.

the class LogoutTest method testLogoutPropagatesToSamlIdentityProviderNameIdPreserved.

@Test
public void testLogoutPropagatesToSamlIdentityProviderNameIdPreserved() throws IOException {
    final RealmResource realm = adminClient.realm(REALM_NAME);
    try (Closeable sales = ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST).setFrontchannelLogout(true).removeAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE).setAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, "http://url").update();
        Closeable idp = new IdentityProviderCreator(realm, addIdentityProvider())) {
        SAMLDocumentHolder samlResponse = logIntoUnsignedSalesAppViaIdp().logoutRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, REDIRECT).nameId(nameIdRef::get).sessionIndex(sessionIndexRef::get).build().getSamlResponse(REDIRECT);
        assertThat(samlResponse.getSamlObject(), isSamlLogoutRequest(BROKER_LOGOUT_SERVICE_URL));
        LogoutRequestType lr = (LogoutRequestType) samlResponse.getSamlObject();
        NameIDType logoutRequestNameID = lr.getNameID();
        assertThat(logoutRequestNameID.getFormat(), is(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.getUri()));
        assertThat(logoutRequestNameID.getValue(), is("a@b.c"));
        assertThat(logoutRequestNameID.getNameQualifier(), is(NAME_QUALIFIER));
        assertThat(logoutRequestNameID.getSPProvidedID(), is(SP_PROVIDED_ID));
        assertThat(logoutRequestNameID.getSPNameQualifier(), is(SP_NAME_QUALIFIER));
    }
}
Also used : SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) RealmResource(org.keycloak.admin.client.resource.RealmResource) Closeable(java.io.Closeable) IdentityProviderCreator(org.keycloak.testsuite.updaters.IdentityProviderCreator) LogoutRequestType(org.keycloak.dom.saml.v2.protocol.LogoutRequestType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) Test(org.junit.Test)

Example 37 with NameIDType

use of org.keycloak.dom.saml.v2.assertion.NameIDType in project keycloak by keycloak.

the class AbstractSamlAuthenticationHandler method handleLoginResponse.

protected AuthOutcome handleLoginResponse(SAMLDocumentHolder responseHolder, boolean postBinding, OnSessionCreated onCreateSession) {
    if (!sessionStore.isLoggingIn()) {
        log.warn("Adapter obtained LoginResponse, however containers session is not aware of sending any request. " + "This may be because the session cookies created by container are not properly configured " + "with SameSite settings. Refer to KEYCLOAK-14103 for more details.");
    }
    final ResponseType responseType = (ResponseType) responseHolder.getSamlObject();
    AssertionType assertion = null;
    if (!isSuccessfulSamlResponse(responseType) || responseType.getAssertions() == null || responseType.getAssertions().isEmpty()) {
        return failed(createAuthChallenge403(responseType));
    }
    try {
        assertion = AssertionUtil.getAssertion(responseHolder, responseType, deployment.getDecryptionKey());
        ConditionsValidator.Builder cvb = new ConditionsValidator.Builder(assertion.getID(), assertion.getConditions(), destinationValidator);
        try {
            cvb.clockSkewInMillis(deployment.getIDP().getAllowedClockSkew());
            cvb.addAllowedAudience(URI.create(deployment.getEntityID()));
            if (responseType.getDestination() != null) {
                // getDestination has been validated to match request URL already so it matches SAML endpoint
                cvb.addAllowedAudience(URI.create(responseType.getDestination()));
            }
        } catch (IllegalArgumentException ex) {
        // warning has been already emitted in DeploymentBuilder
        }
        if (!cvb.build().isValid()) {
            return initiateLogin();
        }
    } catch (Exception e) {
        log.error("Error extracting SAML assertion: " + e.getMessage());
        return failed(CHALLENGE_EXTRACTION_FAILURE);
    }
    Element assertionElement = null;
    if (deployment.getIDP().getSingleSignOnService().validateAssertionSignature()) {
        try {
            assertionElement = getAssertionFromResponse(responseHolder);
            if (!AssertionUtil.isSignatureValid(assertionElement, deployment.getIDP().getSignatureValidationKeyLocator())) {
                log.error("Failed to verify saml assertion signature");
                return failed(CHALLENGE_INVALID_SIGNATURE);
            }
        } catch (Exception e) {
            log.error("Error processing validation of SAML assertion: " + e.getMessage());
            return failed(CHALLENGE_EXTRACTION_FAILURE);
        }
    }
    SubjectType subject = assertion.getSubject();
    SubjectType.STSubType subType = subject.getSubType();
    NameIDType subjectNameID = subType == null ? null : (NameIDType) subType.getBaseID();
    String principalName = subjectNameID == null ? null : subjectNameID.getValue();
    Set<String> roles = new HashSet<>();
    MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
    MultivaluedHashMap<String, String> friendlyAttributes = new MultivaluedHashMap<>();
    Set<StatementAbstractType> statements = assertion.getStatements();
    for (StatementAbstractType statement : statements) {
        if (statement instanceof AttributeStatementType) {
            AttributeStatementType attributeStatement = (AttributeStatementType) statement;
            List<AttributeStatementType.ASTChoiceType> attList = attributeStatement.getAttributes();
            for (AttributeStatementType.ASTChoiceType obj : attList) {
                AttributeType attr = obj.getAttribute();
                if (isRole(attr)) {
                    List<Object> attributeValues = attr.getAttributeValue();
                    if (attributeValues != null) {
                        for (Object attrValue : attributeValues) {
                            String role = getAttributeValue(attrValue);
                            log.debugv("Add role: {0}", role);
                            roles.add(role);
                        }
                    }
                } else {
                    List<Object> attributeValues = attr.getAttributeValue();
                    if (attributeValues != null) {
                        for (Object attrValue : attributeValues) {
                            String value = getAttributeValue(attrValue);
                            if (attr.getName() != null) {
                                attributes.add(attr.getName(), value);
                            }
                            if (attr.getFriendlyName() != null) {
                                friendlyAttributes.add(attr.getFriendlyName(), value);
                            }
                        }
                    }
                }
            }
        }
    }
    if (deployment.getPrincipalNamePolicy() == SamlDeployment.PrincipalNamePolicy.FROM_ATTRIBUTE) {
        if (deployment.getPrincipalAttributeName() != null) {
            String attribute = attributes.getFirst(deployment.getPrincipalAttributeName());
            if (attribute != null)
                principalName = attribute;
            else {
                attribute = friendlyAttributes.getFirst(deployment.getPrincipalAttributeName());
                if (attribute != null)
                    principalName = attribute;
            }
        }
    }
    // use the configured role mappings provider to map roles if necessary.
    if (deployment.getRoleMappingsProvider() != null) {
        roles = deployment.getRoleMappingsProvider().map(principalName, roles);
    }
    // roles should also be there as regular attributes
    // this mainly required for elytron and its ABAC nature
    attributes.put(DEFAULT_ROLE_ATTRIBUTE_NAME, new ArrayList<>(roles));
    AuthnStatementType authn = null;
    for (Object statement : assertion.getStatements()) {
        if (statement instanceof AuthnStatementType) {
            authn = (AuthnStatementType) statement;
            break;
        }
    }
    URI nameFormat = subjectNameID == null ? null : subjectNameID.getFormat();
    String nameFormatString = nameFormat == null ? JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.get() : nameFormat.toString();
    if (deployment.isKeepDOMAssertion() && assertionElement == null) {
        // obtain the assertion from the response to add the DOM document to the principal
        assertionElement = getAssertionFromResponseNoException(responseHolder);
    }
    final SamlPrincipal principal = new SamlPrincipal(assertion, deployment.isKeepDOMAssertion() ? getAssertionDocumentFromElement(assertionElement) : null, principalName, principalName, nameFormatString, attributes, friendlyAttributes);
    final String sessionIndex = authn == null ? null : authn.getSessionIndex();
    final XMLGregorianCalendar sessionNotOnOrAfter = authn == null ? null : authn.getSessionNotOnOrAfter();
    SamlSession account = new SamlSession(principal, roles, sessionIndex, sessionNotOnOrAfter);
    sessionStore.saveAccount(account);
    onCreateSession.onSessionCreated(account);
    // redirect to original request, it will be restored
    String redirectUri = sessionStore.getRedirectUri();
    if (redirectUri != null) {
        facade.getResponse().setHeader("Location", redirectUri);
        facade.getResponse().setStatus(302);
        facade.getResponse().end();
    } else {
        log.debug("IDP initiated invocation");
    }
    log.debug("AUTHENTICATED authn");
    return AuthOutcome.AUTHENTICATED;
}
Also used : SAML2AuthnRequestBuilder(org.keycloak.saml.SAML2AuthnRequestBuilder) KeycloakUriBuilder(org.keycloak.common.util.KeycloakUriBuilder) BaseSAML2BindingBuilder(org.keycloak.saml.BaseSAML2BindingBuilder) Element(org.w3c.dom.Element) URI(java.net.URI) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) AuthnStatementType(org.keycloak.dom.saml.v2.assertion.AuthnStatementType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) SamlSession(org.keycloak.adapters.saml.SamlSession) VerificationException(org.keycloak.common.VerificationException) SignatureException(java.security.SignatureException) KeyManagementException(java.security.KeyManagementException) InvalidKeyException(java.security.InvalidKeyException) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) IOException(java.io.IOException) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) SamlPrincipal(org.keycloak.adapters.saml.SamlPrincipal) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) ConditionsValidator(org.keycloak.saml.validators.ConditionsValidator) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType)

Example 38 with NameIDType

use of org.keycloak.dom.saml.v2.assertion.NameIDType in project keycloak by keycloak.

the class SAMLAttributeQueryParserTest method testSaml20AttributeQuery.

@Test(timeout = 2000000)
public void testSaml20AttributeQuery() throws Exception {
    try (InputStream is = SAMLAttributeQueryParserTest.class.getResourceAsStream("saml20-attributequery.xml")) {
        Object parsedObject = parser.parse(is);
        assertThat(parsedObject, instanceOf(AttributeQueryType.class));
        AttributeQueryType query = (AttributeQueryType) parsedObject;
        assertThat(query.getSignature(), nullValue());
        assertThat(query.getConsent(), nullValue());
        assertThat(query.getIssuer(), not(nullValue()));
        assertThat(query.getIssuer().getValue(), is("https://sp/"));
        NameIDType nameId = (NameIDType) query.getSubject().getSubType().getBaseID();
        assertThat(nameId.getValue(), is("CN=trscavo@uiuc.edu,OU=User,O=NCSA-TEST,C=US"));
    }
}
Also used : InputStream(java.io.InputStream) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AttributeQueryType(org.keycloak.dom.saml.v2.protocol.AttributeQueryType) Test(org.junit.Test)

Example 39 with NameIDType

use of org.keycloak.dom.saml.v2.assertion.NameIDType in project keycloak by keycloak.

the class SAMLSloRequestParserTest method testSaml20SloResponseWithExtension.

@Test(timeout = 2000)
public void testSaml20SloResponseWithExtension() throws Exception {
    try (InputStream is = SAMLSloRequestParserTest.class.getResourceAsStream("KEYCLOAK-4552-saml20-aslo-response-via-extension.xml")) {
        Object parsedObject = parser.parse(is);
        assertThat(parsedObject, instanceOf(LogoutRequestType.class));
        LogoutRequestType resp = (LogoutRequestType) parsedObject;
        assertThat(resp.getSignature(), nullValue());
        assertThat(resp.getConsent(), nullValue());
        assertThat(resp.getIssuer(), not(nullValue()));
        assertThat(resp.getIssuer().getValue(), is("https://sp/"));
        NameIDType nameId = resp.getNameID();
        assertThat(nameId.getValue(), is("G-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"));
        assertThat(resp.getExtensions(), not(nullValue()));
        assertThat(resp.getExtensions().getAny().size(), is(1));
        assertThat(resp.getExtensions().getAny().get(0), instanceOf(Element.class));
        Element el = (Element) resp.getExtensions().getAny().get(0);
        assertThat(el.getLocalName(), is("Asynchronous"));
        assertThat(el.getNamespaceURI(), is("urn:oasis:names:tc:SAML:2.0:protocol:ext:async-slo"));
    }
}
Also used : InputStream(java.io.InputStream) Element(org.w3c.dom.Element) LogoutRequestType(org.keycloak.dom.saml.v2.protocol.LogoutRequestType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) Test(org.junit.Test)

Example 40 with NameIDType

use of org.keycloak.dom.saml.v2.assertion.NameIDType in project keycloak by keycloak.

the class SAMLIdentityProvider method authenticationFinished.

@Override
public void authenticationFinished(AuthenticationSessionModel authSession, BrokeredIdentityContext context) {
    ResponseType responseType = (ResponseType) context.getContextData().get(SAMLEndpoint.SAML_LOGIN_RESPONSE);
    AssertionType assertion = (AssertionType) context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
    SubjectType subject = assertion.getSubject();
    SubjectType.STSubType subType = subject.getSubType();
    if (subType != null) {
        NameIDType subjectNameID = (NameIDType) subType.getBaseID();
        authSession.setUserSessionNote(SAMLEndpoint.SAML_FEDERATED_SUBJECT_NAMEID, subjectNameID.serializeAsString());
    }
    AuthnStatementType authn = (AuthnStatementType) context.getContextData().get(SAMLEndpoint.SAML_AUTHN_STATEMENT);
    if (authn != null && authn.getSessionIndex() != null) {
        authSession.setUserSessionNote(SAMLEndpoint.SAML_FEDERATED_SESSION_INDEX, authn.getSessionIndex());
    }
}
Also used : AuthnStatementType(org.keycloak.dom.saml.v2.assertion.AuthnStatementType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType)

Aggregations

NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)54 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)22 Element (org.w3c.dom.Element)21 Test (org.junit.Test)20 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)19 SubjectType (org.keycloak.dom.saml.v2.assertion.SubjectType)15 QName (javax.xml.namespace.QName)12 List (java.util.List)11 URI (java.net.URI)9 AudienceRestrictionType (org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType)8 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)7 ExtensionsType (org.keycloak.dom.saml.v2.protocol.ExtensionsType)7 StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)7 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)7 Document (org.w3c.dom.Document)7 InputStream (java.io.InputStream)5 HashMap (java.util.HashMap)5 AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)5 AuthnStatementType (org.keycloak.dom.saml.v2.assertion.AuthnStatementType)5 EncryptedAssertionType (org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType)5