Search in sources :

Example 16 with StatusResponseType

use of org.keycloak.dom.saml.v2.protocol.StatusResponseType in project keycloak by keycloak.

the class SAML2LogoutResponseBuilder method buildModel.

public StatusResponseType buildModel() throws ConfigurationException {
    StatusResponseType statusResponse = new StatusResponseType(IDGenerator.create("ID_"), XMLTimeUtil.getIssueInstant());
    // Status
    StatusType statusType = new StatusType();
    StatusCodeType statusCodeType = new StatusCodeType();
    statusCodeType.setValue(JBossSAMLURIConstants.STATUS_SUCCESS.getUri());
    statusType.setStatusCode(statusCodeType);
    statusResponse.setStatus(statusType);
    statusResponse.setInResponseTo(logoutRequestID);
    statusResponse.setIssuer(issuer);
    statusResponse.setDestination(destination);
    if (!this.extensions.isEmpty()) {
        ExtensionsType extensionsType = new ExtensionsType();
        for (NodeGenerator extension : this.extensions) {
            extensionsType.addExtension(extension);
        }
        statusResponse.setExtensions(extensionsType);
    }
    return statusResponse;
}
Also used : StatusType(org.keycloak.dom.saml.v2.protocol.StatusType) ExtensionsType(org.keycloak.dom.saml.v2.protocol.ExtensionsType) StatusCodeType(org.keycloak.dom.saml.v2.protocol.StatusCodeType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType)

Example 17 with StatusResponseType

use of org.keycloak.dom.saml.v2.protocol.StatusResponseType in project keycloak by keycloak.

the class SAMLSloResponseParser method instantiateElement.

@Override
protected StatusResponseType instantiateElement(XMLEventReader xmlEventReader, StartElement element) throws ParsingException {
    SAMLParserUtil.validateAttributeValue(element, SAMLProtocolQNames.ATTR_VERSION, VERSION_2_0);
    String id = StaxParserUtil.getRequiredAttributeValue(element, SAMLProtocolQNames.ATTR_ID);
    XMLGregorianCalendar issueInstant = XMLTimeUtil.parse(StaxParserUtil.getRequiredAttributeValue(element, SAMLProtocolQNames.ATTR_ISSUE_INSTANT));
    StatusResponseType res = new StatusResponseType(id, issueInstant);
    // Let us set the attributes
    super.parseBaseAttributes(element, res);
    return res;
}
Also used : XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType)

Example 18 with StatusResponseType

use of org.keycloak.dom.saml.v2.protocol.StatusResponseType in project keycloak by keycloak.

the class IdentityBrokerService method authenticated.

public Response authenticated(BrokeredIdentityContext context) {
    IdentityProviderModel identityProviderConfig = context.getIdpConfig();
    AuthenticationSessionModel authenticationSession = context.getAuthenticationSession();
    String providerId = identityProviderConfig.getAlias();
    if (!identityProviderConfig.isStoreToken()) {
        if (isDebugEnabled()) {
            logger.debugf("Token will not be stored for identity provider [%s].", providerId);
        }
        context.setToken(null);
    }
    StatusResponseType loginResponse = (StatusResponseType) context.getContextData().get(SAMLEndpoint.SAML_LOGIN_RESPONSE);
    if (loginResponse != null) {
        for (Iterator<SamlAuthenticationPreprocessor> it = SamlSessionUtils.getSamlAuthenticationPreprocessorIterator(session); it.hasNext(); ) {
            loginResponse = it.next().beforeProcessingLoginResponse(loginResponse, authenticationSession);
        }
    }
    session.getContext().setClient(authenticationSession.getClient());
    context.getIdp().preprocessFederatedIdentity(session, realmModel, context);
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    realmModel.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).forEach(mapper -> {
        IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
        target.preprocessFederatedIdentity(session, realmModel, mapper, context);
    });
    FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(providerId, context.getId(), context.getUsername(), context.getToken());
    this.event.event(EventType.IDENTITY_PROVIDER_LOGIN).detail(Details.REDIRECT_URI, authenticationSession.getRedirectUri()).detail(Details.IDENTITY_PROVIDER, providerId).detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    UserModel federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
    boolean shouldMigrateId = false;
    // try to find the user using legacy ID
    if (federatedUser == null && context.getLegacyId() != null) {
        federatedIdentityModel = new FederatedIdentityModel(federatedIdentityModel, context.getLegacyId());
        federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
        shouldMigrateId = true;
    }
    // Check if federatedUser is already authenticated (this means linking social into existing federatedUser account)
    UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authenticationSession);
    if (shouldPerformAccountLinking(authenticationSession, userSession, providerId)) {
        return performAccountLinking(authenticationSession, userSession, context, federatedIdentityModel, federatedUser);
    }
    if (federatedUser == null) {
        logger.debugf("Federated user not found for provider '%s' and broker username '%s'", providerId, context.getUsername());
        String username = context.getModelUsername();
        if (username == null) {
            if (this.realmModel.isRegistrationEmailAsUsername() && !Validation.isBlank(context.getEmail())) {
                username = context.getEmail();
            } else if (context.getUsername() == null) {
                username = context.getIdpConfig().getAlias() + "." + context.getId();
            } else {
                username = context.getUsername();
            }
        }
        username = username.trim();
        context.setModelUsername(username);
        SerializedBrokeredIdentityContext ctx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (ctx0 != null) {
            SerializedBrokeredIdentityContext ctx1 = SerializedBrokeredIdentityContext.serialize(context);
            ctx1.saveToAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
            logger.warnv("Nested first broker flow detected: {0} -> {1}", ctx0.getIdentityProviderId(), ctx1.getIdentityProviderId());
            logger.debug("Resuming last execution");
            URI redirect = new AuthenticationFlowURLHelper(session, realmModel, session.getContext().getUri()).getLastExecutionUrl(authenticationSession);
            return Response.status(Status.FOUND).location(redirect).build();
        }
        logger.debug("Redirecting to flow for firstBrokerLogin");
        boolean forwardedPassiveLogin = "true".equals(authenticationSession.getAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN));
        // Redirect to firstBrokerLogin after successful login and ensure that previous authentication state removed
        AuthenticationProcessor.resetFlow(authenticationSession, LoginActionsService.FIRST_BROKER_LOGIN_PATH);
        // Set the FORWARDED_PASSIVE_LOGIN note (if needed) after resetting the session so it is not lost.
        if (forwardedPassiveLogin) {
            authenticationSession.setAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN, "true");
        }
        SerializedBrokeredIdentityContext ctx = SerializedBrokeredIdentityContext.serialize(context);
        ctx.saveToAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        URI redirect = LoginActionsService.firstBrokerLoginProcessor(session.getContext().getUri()).queryParam(Constants.CLIENT_ID, authenticationSession.getClient().getClientId()).queryParam(Constants.TAB_ID, authenticationSession.getTabId()).build(realmModel.getName());
        return Response.status(302).location(redirect).build();
    } else {
        Response response = validateUser(authenticationSession, federatedUser, realmModel);
        if (response != null) {
            return response;
        }
        updateFederatedIdentity(context, federatedUser);
        if (shouldMigrateId) {
            migrateFederatedIdentityId(context, federatedUser);
        }
        authenticationSession.setAuthenticatedUser(federatedUser);
        return finishOrRedirectToPostBrokerLogin(authenticationSession, context, false);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) AuthenticationFlowURLHelper(org.keycloak.services.util.AuthenticationFlowURLHelper) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) URI(java.net.URI) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) UserModel(org.keycloak.models.UserModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) SamlAuthenticationPreprocessor(org.keycloak.protocol.saml.preprocessor.SamlAuthenticationPreprocessor)

Example 19 with StatusResponseType

use of org.keycloak.dom.saml.v2.protocol.StatusResponseType in project keycloak by keycloak.

the class SAMLServletAdapterTest method testInvalidCredentialsEcpFlow.

@Test
public void testInvalidCredentialsEcpFlow() throws Exception {
    Response authnRequestResponse = AdminClientUtil.createResteasyClient().target(ecpSPPage.toString()).request().header("Accept", "text/html; application/vnd.paos+xml").header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'").get();
    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));
    Iterator<javax.xml.soap.Node> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(new QName("urn:liberty:paos:2003-08", "Request"));
    it.next();
    it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    javax.xml.soap.Node ecpRequestHeader = it.next();
    NodeList idpList = ((SOAPHeaderElement) ecpRequestHeader).getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "IDPList");
    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));
    NodeList idpEntries = idpList.item(0).getChildNodes();
    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));
    String singleSignOnService = null;
    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");
        singleSignOnService = location.getNodeValue();
    }
    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());
    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "baspassword";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());
    Response authenticationResponse = AdminClientUtil.createResteasyClient().target(singleSignOnService).request().header(HttpHeaders.AUTHORIZATION, authHeader).post(Entity.entity(DocumentUtil.asString(authenticationRequest), "application/soap+xml"));
    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));
    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));
    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();
    Assert.assertThat(samlResponse, notNullValue());
    StatusResponseType responseType = (StatusResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();
    Assert.assertThat(statusCode.getStatusCode().getValue().toString(), is(not(JBossSAMLURIConstants.STATUS_SUCCESS.get())));
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) NamedNodeMap(org.w3c.dom.NamedNodeMap) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) StatusCodeType(org.keycloak.dom.saml.v2.protocol.StatusCodeType) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 20 with StatusResponseType

use of org.keycloak.dom.saml.v2.protocol.StatusResponseType in project keycloak by keycloak.

the class ArtifactBindingWithResolutionServiceTest method testReceiveArtifactLogoutFullWithRedirect.

@Test
public void testReceiveArtifactLogoutFullWithRedirect() throws InterruptedException {
    getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST).setAttribute(SamlProtocol.SAML_ARTIFACT_RESOLUTION_SERVICE_URL_ATTRIBUTE, "http://127.0.0.1:8082/").setAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, "http://url").setFrontchannelLogout(true).update());
    SamlClientBuilder builder = new SamlClientBuilder();
    CreateArtifactMessageStepBuilder camb = new CreateArtifactMessageStepBuilder(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, REDIRECT, builder);
    ArtifactResolutionService ars = new ArtifactResolutionService("http://127.0.0.1:8082/");
    Thread arsThread = new Thread(ars);
    try {
        arsThread.start();
        synchronized (ars) {
            ars.wait();
            SAMLDocumentHolder samlResponse = builder.authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, REDIRECT).setProtocolBinding(JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.getUri()).build().login().user(bburkeUser).build().processSamlResponse(REDIRECT).transformObject(x -> {
                SAML2Object samlObj = extractNameIdAndSessionIndexAndTerminate(x);
                setArtifactResolutionServiceLogoutRequest(ars);
                return samlObj;
            }).build().artifactMessage(camb).build().getSamlResponse(REDIRECT);
            assertThat(samlResponse.getSamlObject(), instanceOf(StatusResponseType.class));
            StatusResponseType srt = (StatusResponseType) samlResponse.getSamlObject();
            assertThat(srt, isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
            assertThat(camb.getLastArtifact(), is(ars.getLastArtifactResolve().getArtifact()));
        }
    } finally {
        ars.stop();
        arsThread.join();
    }
}
Also used : SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) ArtifactResolutionService(org.keycloak.testsuite.util.ArtifactResolutionService) CreateArtifactMessageStepBuilder(org.keycloak.testsuite.util.saml.CreateArtifactMessageStepBuilder) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Test(org.junit.Test)

Aggregations

StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)22 Test (org.junit.Test)13 SAMLDocumentHolder (org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder)9 SamlClientBuilder (org.keycloak.testsuite.util.SamlClientBuilder)7 ArtifactResponseType (org.keycloak.dom.saml.v2.protocol.ArtifactResponseType)6 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)6 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)5 QName (javax.xml.namespace.QName)4 SAML2Object (org.keycloak.dom.saml.v2.SAML2Object)4 ExtensionsType (org.keycloak.dom.saml.v2.protocol.ExtensionsType)4 LogoutRequestType (org.keycloak.dom.saml.v2.protocol.LogoutRequestType)4 ParsingException (org.keycloak.saml.common.exceptions.ParsingException)4 Document (org.w3c.dom.Document)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Response (javax.ws.rs.core.Response)3 StatusCodeType (org.keycloak.dom.saml.v2.protocol.StatusCodeType)3 StatusType (org.keycloak.dom.saml.v2.protocol.StatusType)3 UserSessionModel (org.keycloak.models.UserSessionModel)3 ConfigurationException (org.keycloak.saml.common.exceptions.ConfigurationException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2