Package org.picketlink.identity.federation.web.util

Examples of org.picketlink.identity.federation.web.util.IDPWebRequestUtil


            || containsSAMLRequestMessage || containsSAMLResponseMessage)
      {
         request = restoreRequestInfoFromSP(request, session);
      }

      IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);

      Document samlErrorResponse = null;
      // Look for unauthorized status
      if (response.getStatus() == HttpServletResponse.SC_FORBIDDEN)
      {
         try
         {
            samlErrorResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                  getIdentityURL(), this.idpConfiguration.isSupportsSignature());

            IDPWebRequestUtil.WebRequestUtilHolder holder = webRequestUtil.getHolder();
            holder.setResponseDoc(samlErrorResponse).setDestination(referer).setRelayState(relayState)
                  .setAreWeSendingRequest(false).setPrivateKey(null).setSupportSignature(false)
                  .setServletResponse(response);
            holder.setPostBindingRequested(webRequestUtil.hasSAMLRequestInPostProfile());

            if (this.idpConfiguration.isSupportsSignature())
            {
               holder.setSupportSignature(true).setPrivateKey(keyManager.getSigningKey());
            }

            holder.setStrictPostBinding(this.idpConfiguration.isStrictPostBinding());

            webRequestUtil.send(holder);
         }
         catch (GeneralSecurityException e)
         {
            throw new ServletException(e);
         }
View Full Code Here


            || containsSAMLRequestMessage || containsSAMLResponseMessage)
      {
         request = restoreRequestInfoFromSP(request, session);
      }

      IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);

      Document samlErrorResponse = null;
      // Look for unauthorized status
      if (response.getStatus() == HttpServletResponse.SC_FORBIDDEN)
      {
         try
         {
            samlErrorResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                  getIdentityURL(), this.idpConfiguration.isSupportsSignature());

            IDPWebRequestUtil.WebRequestUtilHolder holder = webRequestUtil.getHolder();
            holder.setResponseDoc(samlErrorResponse).setDestination(referer).setRelayState(relayState)
                  .setAreWeSendingRequest(false).setPrivateKey(null).setSupportSignature(false)
                  .setServletResponse(response);
            holder.setPostBindingRequested(webRequestUtil.hasSAMLRequestInPostProfile());

            if (this.idpConfiguration.isSupportsSignature())
            {
               holder.setSupportSignature(true).setPrivateKey(keyManager.getSigningKey());
            }

            holder.setStrictPostBinding(this.idpConfiguration.isStrictPostBinding());

            webRequestUtil.send(holder);
         }
         catch (GeneralSecurityException e)
         {
            throw new ServletException(e);
         }
View Full Code Here

            if (trace)
                log.trace("Login Filters have not been configured");
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);
        webRequestUtil.setCanonicalizationMethod(canonicalizationMethod);

        boolean willSendRequest = true;

        if (userPrincipal != null) {
            if (trace) {
                log.trace("Retrieved saml message and relay state from session");
                log.trace("saml Request message=" + samlRequestMessage + "::relay state=" + relayState);
                log.trace("saml Response message=" + samlResponseMessage + "::relay state=" + relayState);
            }
            session.removeAttribute(GeneralConstants.SAML_REQUEST_KEY);
            session.removeAttribute(GeneralConstants.SAML_RESPONSE_KEY);

            if (isNotNull(relayState))
                session.removeAttribute(GeneralConstants.RELAY_STATE);

            SAMLDocumentHolder samlDocumentHolder = null;
            SAML2Object samlObject = null;
            String destination = null;
            Document samlResponse = null;

            if (samlResponseMessage != null) {
                StatusResponseType statusResponseType = null;
                try {
                    samlDocumentHolder = webRequestUtil.getSAMLDocumentHolder(samlResponseMessage);
                    samlObject = samlDocumentHolder.getSamlObject();

                    boolean isPost = webRequestUtil.hasSAMLRequestInPostProfile();
                    boolean isValid = validate(request.getRemoteAddr(), request.getQueryString(), new SessionHolder(
                            samlResponseMessage, null), isPost);

                    if (!isValid)
                        throw new GeneralSecurityException("Validation check failed");

                    String issuer = null;
                    IssuerInfoHolder idpIssuer = new IssuerInfoHolder(this.identityURL);
                    ProtocolContext protocolContext = new HTTPContext(request, response, context);
                    // Create the request/response
                    SAML2HandlerRequest saml2HandlerRequest = new DefaultSAML2HandlerRequest(protocolContext,
                            idpIssuer.getIssuer(), samlDocumentHolder, HANDLER_TYPE.IDP);

                    saml2HandlerRequest.setRelayState(relayState);

                    SAML2HandlerResponse saml2HandlerResponse = new DefaultSAML2HandlerResponse();

                    Set<SAML2Handler> handlers = chain.handlers();

                    if (samlObject instanceof StatusResponseType) {
                        statusResponseType = (StatusResponseType) samlObject;
                        issuer = statusResponseType.getIssuer().getValue();
                        webRequestUtil.isTrusted(issuer);

                        if (handlers != null) {
                            for (SAML2Handler handler : handlers) {
                                handler.reset();
                                handler.handleStatusResponseType(saml2HandlerRequest, saml2HandlerResponse);
                                willSendRequest = saml2HandlerResponse.getSendRequest();
                            }
                        }
                    } else
                        throw new RuntimeException(ErrorCodes.UNSUPPORTED_TYPE + "Unknown type:"
                                + samlObject.getClass().getName());

                    samlResponse = saml2HandlerResponse.getResultingDocument();
                    relayState = saml2HandlerResponse.getRelayState();

                    destination = saml2HandlerResponse.getDestination();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            } else
            // Send valid saml response after processing the request
            if (samlRequestMessage != null) {
                // Get the SAML Request Message
                RequestAbstractType requestAbstractType = null;

                try {
                    samlDocumentHolder = webRequestUtil.getSAMLDocumentHolder(samlRequestMessage);
                    samlObject = samlDocumentHolder.getSamlObject();

                    boolean isPost = webRequestUtil.hasSAMLRequestInPostProfile();
                    boolean isValid = validate(request.getRemoteAddr(), request.getQueryString(), new SessionHolder(
                            samlRequestMessage, null), isPost);

                    if (!isValid)
                        throw new GeneralSecurityException(ErrorCodes.VALIDATION_CHECK_FAILED + "Validation check failed");

                    String issuer = null;
                    IssuerInfoHolder idpIssuer = new IssuerInfoHolder(this.identityURL);
                    ProtocolContext protocolContext = new HTTPContext(request, response, context);
                    // Create the request/response
                    SAML2HandlerRequest saml2HandlerRequest = new DefaultSAML2HandlerRequest(protocolContext,
                            idpIssuer.getIssuer(), samlDocumentHolder, HANDLER_TYPE.IDP);
                    saml2HandlerRequest.setRelayState(relayState);

                    // Set the options on the handler request
                    Map<String, Object> requestOptions = new HashMap<String, Object>();
                    requestOptions.put(GeneralConstants.ROLE_GENERATOR, roleGenerator);
                    requestOptions.put(GeneralConstants.CONFIGURATION, this.idpConfiguration);

                    Map<String, Object> attribs = this.attribManager.getAttributes(userPrincipal, attributeKeys);
                    requestOptions.put(GeneralConstants.ATTRIBUTES, attribs);

                    saml2HandlerRequest.setOptions(requestOptions);

                    List<String> roles = (List<String>) session.getAttribute(GeneralConstants.ROLES_ID);
                    if (roles == null) {
                        roles = roleGenerator.generateRoles(userPrincipal);
                        session.setAttribute(GeneralConstants.ROLES_ID, roles);
                    }

                    SAML2HandlerResponse saml2HandlerResponse = new DefaultSAML2HandlerResponse();

                    Set<SAML2Handler> handlers = chain.handlers();

                    if (samlObject instanceof RequestAbstractType) {
                        requestAbstractType = (RequestAbstractType) samlObject;
                        issuer = requestAbstractType.getIssuer().getValue();
                        webRequestUtil.isTrusted(issuer);

                        if (handlers != null) {
                            for (SAML2Handler handler : handlers) {
                                handler.handleRequestType(saml2HandlerRequest, saml2HandlerResponse);
                                willSendRequest = saml2HandlerResponse.getSendRequest();
                            }
                        }
                    } else
                        throw new RuntimeException(ErrorCodes.UNSUPPORTED_TYPE + "Unknown type:"
                                + samlObject.getClass().getName());

                    samlResponse = saml2HandlerResponse.getResultingDocument();
                    relayState = saml2HandlerResponse.getRelayState();

                    destination = saml2HandlerResponse.getDestination();

                } catch (IssuerNotTrustedException e) {
                    if (trace)
                        log.trace("Exception:", e);

                    samlResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_REQUEST_DENIED.get(),
                            this.identityURL, this.signOutgoingMessages);
                } catch (ParsingException e) {
                    if (trace)
                        log.trace("Exception:", e);

                    samlResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                            this.identityURL, this.signOutgoingMessages);
                } catch (ConfigurationException e) {
                    if (trace)
                        log.trace("Exception:", e);

                    samlResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                            this.identityURL, this.signOutgoingMessages);
                } catch (IssueInstantMissingException e) {
                    if (trace)
                        log.trace("Exception:", e);

                    samlResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                            this.identityURL, this.signOutgoingMessages);
                } catch (GeneralSecurityException e) {
                    if (trace)
                        log.trace("Security Exception:", e);

                    samlResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                            this.identityURL, this.signOutgoingMessages);
                } catch (Exception e) {
                    if (trace)
                        log.trace("Exception:", e);

                    samlResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                            this.identityURL, this.signOutgoingMessages);
                }

            } else {
                log.error("No SAML Request Message");
                if (trace)
                    log.trace("Referer=" + referer);

                try {
                    sendErrorResponseToSP(referer, response, relayState, webRequestUtil);
                    return;
                } catch (ConfigurationException e) {
                    if (trace)
                        log.trace(e);
                }
            }

            try {
                if (samlResponse == null)
                    throw new ServletException(ErrorCodes.NULL_VALUE + "SAML Response has not been generated");

                WebRequestUtilHolder holder = webRequestUtil.getHolder();
                holder.setResponseDoc(samlResponse).setDestination(destination).setRelayState(relayState)
                        .setAreWeSendingRequest(willSendRequest).setPrivateKey(null).setSupportSignature(false)
                        .setServletResponse(response);
                holder.setPostBindingRequested(true);

                if (this.signOutgoingMessages) {
                    holder.setPrivateKey(keyManager.getSigningKey()).setSupportSignature(true);
                }

                if (strictPostBinding)
                    holder.setStrictPostBinding(strictPostBinding);
                webRequestUtil.send(holder);
            } catch (ParsingException e) {
                if (trace)
                    log.trace(e);
            } catch (GeneralSecurityException e) {
                if (trace)
View Full Code Here

     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void handleUnauthorizedResponse(Request request, Response response) throws IOException, ServletException {
        IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);
        Document samlErrorResponse = null;
        String referer = request.getHeader("Referer");
        String relayState = request.getParameter(GeneralConstants.RELAY_STATE);

        try {
            samlErrorResponse = webRequestUtil.getErrorResponse(referer, JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                    getIdentityURL(), this.idpConfiguration.isSupportsSignature());

            WebRequestUtilHolder holder = webRequestUtil.getHolder();
            holder.setResponseDoc(samlErrorResponse).setDestination(referer).setRelayState(relayState)
                    .setAreWeSendingRequest(false).setPrivateKey(null).setSupportSignature(false).setServletResponse(response)
                    .setErrorResponse(true);
            holder.setPostBindingRequested(webRequestUtil.hasSAMLRequestInPostProfile());

            if (this.idpConfiguration.isSupportsSignature()) {
                holder.setSupportSignature(true).setPrivateKey(keyManager.getSigningKey());
            }

            holder.setStrictPostBinding(this.idpConfiguration.isStrictPostBinding());

            webRequestUtil.send(holder);
        } catch (GeneralSecurityException e) {
            throw new ServletException(e);
        }
    }
View Full Code Here

        return principal;
    }

    protected void handleSAML11(Request request, Response response) throws ServletException, IOException {
        try {
            IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);

            Principal userPrincipal = request.getPrincipal();
            String contextPath = getContextPath();

            String target = request.getParameter(SAML11Constants.TARGET);

            Session session = request.getSessionInternal();
            SAML11AssertionType saml11Assertion = (SAML11AssertionType) session.getNote("SAML11");
            if (saml11Assertion == null) {
                SAML11ProtocolContext saml11Protocol = new SAML11ProtocolContext();
                saml11Protocol.setIssuerID(getIdentityURL());
                SAML11SubjectType subject = new SAML11SubjectType();
                SAML11SubjectTypeChoice subjectChoice = new SAML11SubjectTypeChoice(new SAML11NameIdentifierType(
                        userPrincipal.getName()));
                subject.setChoice(subjectChoice);
                saml11Protocol.setSubjectType(subject);

                PicketLinkCoreSTS.instance().issueToken(saml11Protocol);
                saml11Assertion = saml11Protocol.getIssuedAssertion();
                session.setNote("SAML11", saml11Assertion);

                if (AssertionUtil.hasExpired(saml11Assertion)) {
                    saml11Protocol.setIssuedAssertion(saml11Assertion);
                    PicketLinkCoreSTS.instance().renewToken(saml11Protocol);
                    saml11Assertion = saml11Protocol.getIssuedAssertion();
                    session.setNote("SAML11", saml11Assertion);
                }
            }
            GenericPrincipal genericPrincipal = (GenericPrincipal) userPrincipal;
            String[] roles = genericPrincipal.getRoles();
            SAML11AttributeStatementType attributeStatement = this.createAttributeStatement(Arrays.asList(roles));
            if (attributeStatement != null) {
                saml11Assertion.add(attributeStatement);
            }

            // Send it as SAMLResponse
            String id = IDGenerator.create("ID_");
            SAML11ResponseType saml11Response = new SAML11ResponseType(id, XMLTimeUtil.getIssueInstant());
            saml11Response.add(saml11Assertion);
            saml11Response.setStatus(SAML11StatusType.successType());

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            SAML11ResponseWriter writer = new SAML11ResponseWriter(StaxUtil.getXMLStreamWriter(baos));
            writer.write(saml11Response);

            Document samlResponse = DocumentUtil.getDocument(new ByteArrayInputStream(baos.toByteArray()));

            WebRequestUtilHolder holder = webRequestUtil.getHolder();
            holder.setResponseDoc(samlResponse).setDestination(target).setRelayState("").setAreWeSendingRequest(false)
                    .setPrivateKey(null).setSupportSignature(false).setServletResponse(response);

            if (enableAudit) {
                PicketLinkAuditEvent auditEvent = new PicketLinkAuditEvent(AuditLevel.INFO);
                auditEvent.setType(PicketLinkAuditEventType.RESPONSE_TO_SP);
                auditEvent.setDestination(target);
                auditEvent.setWhoIsAuditing(contextPath);
                auditHelper.audit(auditEvent);
            }

            response.getCoyoteResponse().recycle();

            webRequestUtil.send(holder);
        } catch (GeneralSecurityException e) {
            logger.samlIDPHandlingSAML11Error(e);
            throw new ServletException();
        }
    }
View Full Code Here

        // Determine the transport mechanism
        boolean isSecure = request.isSecure();
        String loginType = determineLoginType(isSecure);

        IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);

        try {
            samlDocumentHolder = webRequestUtil.getSAMLDocumentHolder(samlRequestMessage);
            samlObject = samlDocumentHolder.getSamlObject();

            if (!(samlObject instanceof RequestAbstractType)) {
                throw logger.wrongTypeError(samlObject.getClass().getName());
            }

            // Get the SAML Request Message
            RequestAbstractType requestAbstractType = (RequestAbstractType) samlObject;
            String issuer = requestAbstractType.getIssuer().getValue();

            if (samlRequestMessage == null)
                throw logger.samlIDPValidationCheckFailed();

            IssuerInfoHolder idpIssuer = new IssuerInfoHolder(getIdentityURL());
            ProtocolContext protocolContext = new HTTPContext(request, response, getContext().getServletContext());
            // Create the request/response
            SAML2HandlerRequest saml2HandlerRequest = new DefaultSAML2HandlerRequest(protocolContext, idpIssuer.getIssuer(),
                    samlDocumentHolder, HANDLER_TYPE.IDP);
            saml2HandlerRequest.setRelayState(relayState);
            if (StringUtil.isNotNull(loginType)) {
                saml2HandlerRequest.addOption(GeneralConstants.LOGIN_TYPE, loginType);
            }

            String assertionID = (String) session.getSession().getAttribute(GeneralConstants.ASSERTION_ID);

            // Set the options on the handler request
            Map<String, Object> requestOptions = new HashMap<String, Object>();

            requestOptions.put(GeneralConstants.IGNORE_SIGNATURES, willIgnoreSignatureOfCurrentRequest(issuer));
            requestOptions.put(GeneralConstants.SP_SSO_METADATA_DESCRIPTOR, spSSOMetadataMap.get(issuer));
            requestOptions.put(GeneralConstants.ROLE_GENERATOR, roleGenerator);
            requestOptions.put(GeneralConstants.CONFIGURATION, this.idpConfiguration);
            requestOptions.put(GeneralConstants.SAML_IDP_STRICT_POST_BINDING, this.idpConfiguration.isStrictPostBinding());
            requestOptions.put(GeneralConstants.SUPPORTS_SIGNATURES, this.idpConfiguration.isSupportsSignature());

            if (assertionID != null)
                requestOptions.put(GeneralConstants.ASSERTION_ID, assertionID);

            if (this.keyManager != null) {
                PublicKey validatingKey = getIssuerPublicKey(request, issuer);
                requestOptions.put(GeneralConstants.SENDER_PUBLIC_KEY, validatingKey);
                requestOptions.put(GeneralConstants.DECRYPTING_KEY, keyManager.getSigningKey());
            }

            // if this is a SAML AuthnRequest load the roles using the generator.
            if (requestAbstractType instanceof AuthnRequestType) {
                List<String> roles = roleGenerator.generateRoles(userPrincipal);
                session.getSession().setAttribute(GeneralConstants.ROLES_ID, roles);

                Map<String, Object> attribs = this.attribManager.getAttributes(
                                     passUserPrincipalToAttributeManager == true
                                         ?  request.getUserPrincipal()
                                         : userPrincipal,
                                     attributeKeys);
                requestOptions.put(GeneralConstants.ATTRIBUTES, attribs);
            }

            if (auditHelper != null) {
                requestOptions.put(GeneralConstants.AUDIT_HELPER, auditHelper);
                requestOptions.put(GeneralConstants.CONTEXT_PATH, contextPath);
            }

            saml2HandlerRequest.setOptions(requestOptions);

            SAML2HandlerResponse saml2HandlerResponse = new DefaultSAML2HandlerResponse();

            Set<SAML2Handler> handlers = chain.handlers();

            logger.trace("Handlers are=" + handlers);

            // the trusted domains is done by a handler
            // webRequestUtil.isTrusted(issuer);

            if (handlers != null) {
                try {
                    chainLock.lock();
                    for (SAML2Handler handler : handlers) {
                        handler.handleRequestType(saml2HandlerRequest, saml2HandlerResponse);
                        willSendRequest = saml2HandlerResponse.getSendRequest();
                    }
                } finally {
                    chainLock.unlock();
                }
            }

            samlResponse = saml2HandlerResponse.getResultingDocument();
            relayState = saml2HandlerResponse.getRelayState();

            destination = saml2HandlerResponse.getDestination();

            requestedPostProfile = saml2HandlerResponse.isPostBindingForResponse();
            destinationQueryStringWithSignature = saml2HandlerResponse.getDestinationQueryStringWithSignature();
        } catch (Exception e) {
            String status = JBossSAMLURIConstants.STATUS_AUTHNFAILED.get();
            if (e instanceof IssuerNotTrustedException || e.getCause() instanceof IssuerNotTrustedException) {
                status = JBossSAMLURIConstants.STATUS_REQUEST_DENIED.get();
            }
            logger.samlIDPRequestProcessingError(e);
            samlResponse = webRequestUtil.getErrorResponse(referer, status, getIdentityURL(),
                    this.idpConfiguration.isSupportsSignature());
            isErrorResponse = true;
        } finally {
            try {
                // if the destination is null, probably because some error occur during authentication, use the AuthnRequest
                // AssertionConsumerServiceURL as the destination
                if (destination == null && samlObject instanceof AuthnRequestType) {
                    AuthnRequestType authRequest = (AuthnRequestType) samlObject;

                    destination = authRequest.getAssertionConsumerServiceURL().toASCIIString();
                }

                // if destination is still empty redirect the user to the identity url. If the user is already authenticated he
                // will be probably redirected to the idp hosted page.
                if (destination == null) {
                    response.sendRedirect(getIdentityURL());
                } else {
                    WebRequestUtilHolder holder = webRequestUtil.getHolder();
                    holder.setResponseDoc(samlResponse).setDestination(destination).setRelayState(relayState)
                            .setAreWeSendingRequest(willSendRequest).setPrivateKey(null).setSupportSignature(false)
                            .setErrorResponse(isErrorResponse).setServletResponse(response)
                            .setDestinationQueryStringWithSignature(destinationQueryStringWithSignature);

                    holder.setStrictPostBinding(this.idpConfiguration.isStrictPostBinding());

                    if (requestedPostProfile != null)
                        holder.setPostBindingRequested(requestedPostProfile);
                    else
                        holder.setPostBindingRequested(webRequestUtil.hasSAMLRequestInPostProfile());

                    if (this.idpConfiguration.isSupportsSignature()) {
                        holder.setPrivateKey(keyManager.getSigningKey()).setSupportSignature(true);
                    }

                    if (holder.isPostBinding())
                        recycle(response);

                    if (enableAudit) {
                        PicketLinkAuditEvent auditEvent = new PicketLinkAuditEvent(AuditLevel.INFO);
                        auditEvent.setType(PicketLinkAuditEventType.RESPONSE_TO_SP);
                        auditEvent.setDestination(destination);
                        auditEvent.setWhoIsAuditing(contextPath);
                        auditHelper.audit(auditEvent);
                    }

                    webRequestUtil.send(holder);
                }
            } catch (ParsingException e) {
                logger.samlAssertionPasingFailed(e);
            } catch (GeneralSecurityException e) {
                logger.trace("Security Exception:", e);
View Full Code Here

        String referer = request.getHeader("Referer");

        cleanUpSessionNote(request);

        IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);

        try {
            samlDocumentHolder = webRequestUtil.getSAMLDocumentHolder(samlResponseMessage);
            samlObject = samlDocumentHolder.getSamlObject();

            if (!(samlObject instanceof StatusResponseType)) {
                throw logger.wrongTypeError(samlObject.getClass().getName());
            }

            StatusResponseType statusResponseType = (StatusResponseType) samlObject;
            String issuer = statusResponseType.getIssuer().getValue();

            boolean isValid = samlResponseMessage != null;

            if (!isValid)
                throw logger.samlIDPValidationCheckFailed();

            IssuerInfoHolder idpIssuer = new IssuerInfoHolder(getIdentityURL());
            ProtocolContext protocolContext = new HTTPContext(request, response, getContext().getServletContext());
            // Create the request/response
            SAML2HandlerRequest saml2HandlerRequest = new DefaultSAML2HandlerRequest(protocolContext, idpIssuer.getIssuer(),
                    samlDocumentHolder, HANDLER_TYPE.IDP);
            Map<String, Object> options = new HashMap<String, Object>();

            if (this.idpConfiguration.isSupportsSignature() || this.idpConfiguration.isEncrypt()) {
                PublicKey publicKey = getIssuerPublicKey(request, issuer);
                options.put(GeneralConstants.SENDER_PUBLIC_KEY, publicKey);
            }

            options.put(GeneralConstants.SAML_IDP_STRICT_POST_BINDING, this.idpConfiguration.isStrictPostBinding());
            options.put(GeneralConstants.SUPPORTS_SIGNATURES, this.idpConfiguration.isSupportsSignature());
            if (auditHelper != null) {
                options.put(GeneralConstants.AUDIT_HELPER, auditHelper);
                options.put(GeneralConstants.CONTEXT_PATH, contextPath);
            }

            saml2HandlerRequest.setOptions(options);
            saml2HandlerRequest.setRelayState(relayState);

            SAML2HandlerResponse saml2HandlerResponse = new DefaultSAML2HandlerResponse();

            Set<SAML2Handler> handlers = chain.handlers();

            // the trusted domains is done by a handler
            // webRequestUtil.isTrusted(issuer);

            if (handlers != null) {
                try {
                    chainLock.lock();
                    for (SAML2Handler handler : handlers) {
                        handler.reset();
                        handler.handleStatusResponseType(saml2HandlerRequest, saml2HandlerResponse);
                        willSendRequest = saml2HandlerResponse.getSendRequest();
                    }
                } finally {
                    chainLock.unlock();
                }
            }

            samlResponse = saml2HandlerResponse.getResultingDocument();
            relayState = saml2HandlerResponse.getRelayState();

            destination = saml2HandlerResponse.getDestination();
            requestedPostProfile = saml2HandlerResponse.isPostBindingForResponse();
            destinationQueryStringWithSignature = saml2HandlerResponse.getDestinationQueryStringWithSignature();
        } catch (Exception e) {
            String status = JBossSAMLURIConstants.STATUS_AUTHNFAILED.get();
            if (e instanceof IssuerNotTrustedException) {
                status = JBossSAMLURIConstants.STATUS_REQUEST_DENIED.get();
            }
            logger.samlIDPRequestProcessingError(e);
            samlResponse = webRequestUtil.getErrorResponse(referer, status, getIdentityURL(),
                    this.idpConfiguration.isSupportsSignature());
            isErrorResponse = true;
        } finally {
            try {
                WebRequestUtilHolder holder = webRequestUtil.getHolder();
                if (destination == null)
                    throw new ServletException(logger.nullValueError("Destination"));
                holder.setResponseDoc(samlResponse).setDestination(destination).setRelayState(relayState)
                        .setAreWeSendingRequest(willSendRequest).setPrivateKey(null).setSupportSignature(false)
                        .setErrorResponse(isErrorResponse).setServletResponse(response)
                        .setPostBindingRequested(requestedPostProfile)
                        .setDestinationQueryStringWithSignature(destinationQueryStringWithSignature);

                /*
                 * if (requestedPostProfile) holder.setPostBindingRequested(requestedPostProfile); else
                 * holder.setPostBindingRequested(postProfile);
                 */

                if (this.idpConfiguration.isSupportsSignature()) {
                    holder.setPrivateKey(keyManager.getSigningKey()).setSupportSignature(true);
                }

                holder.setStrictPostBinding(this.idpConfiguration.isStrictPostBinding());

                if (holder.isPostBinding())
                    recycle(response);

                if (enableAudit) {
                    PicketLinkAuditEvent auditEvent = new PicketLinkAuditEvent(AuditLevel.INFO);
                    auditEvent.setType(PicketLinkAuditEventType.RESPONSE_TO_SP);
                    auditEvent.setWhoIsAuditing(contextPath);
                    auditEvent.setDestination(destination);
                    auditHelper.audit(auditEvent);
                }
                webRequestUtil.send(holder);
            } catch (ParsingException e) {
                logger.samlAssertionPasingFailed(e);
            } catch (GeneralSecurityException e) {
                logger.trace("Security Exception:", e);
            }
View Full Code Here

TOP

Related Classes of org.picketlink.identity.federation.web.util.IDPWebRequestUtil

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.